defineLogicFunction
Define logic functions and their triggers
defineLogicFunction
Define logic functions and their triggers
Each function file uses Available trigger types:The
In your handler, access the forwarded headers like this:Key points:
defineLogicFunction() to export a configuration with a handler and optional triggers.src/logic-functions/createPostCard.logic-function.ts
- httpRoute: Exposes your function on an HTTP path and method under the
/s/endpoint:
e.g.path: '/post-card/create'is callable athttps://your-twenty-server.com/s/post-card/create
- cron: Runs your function on a schedule using a CRON expression.
- databaseEvent: Runs on workspace object lifecycle events. When the event operation is
updated, specific fields to listen to can be specified in theupdatedFieldsarray. If left undefined or empty, any update will trigger the function.
e.g.person.updated,*.created,company.*
You can also manually execute a function using the CLI:You can watch logs with:
Route trigger payload
When a route trigger invokes your logic function, it receives aRoutePayload object that follows the
AWS HTTP API v2 format.
Import the RoutePayload type from twenty-sdk:RoutePayload type has the following structure:| Property | Type | Description | Example |
|---|---|---|---|
headers | Record<string, string | undefined> | HTTP headers (only those listed in forwardedRequestHeaders) | see section below |
queryStringParameters | Record<string, string | undefined> | Query string parameters (multiple values joined with commas) | /users?ids=1&ids=2&ids=3&name=Alice -> { ids: '1,2,3', name: 'Alice' } |
pathParameters | Record<string, string | undefined> | Path parameters extracted from the route pattern | /users/:id, /users/123 -> { id: '123' } |
body | object | null | Parsed request body (JSON) | { id: 1 } -> { id: 1 } |
isBase64Encoded | boolean | Whether the body is base64 encoded | |
requestContext.http.method | string | HTTP method (GET, POST, PUT, PATCH, DELETE) | |
requestContext.http.path | string | Raw request path |
forwardedRequestHeaders
By default, HTTP headers from incoming requests are not passed to your logic function for security reasons. To access specific headers, list them in theforwardedRequestHeaders array:Header names are normalized to lowercase. Access them using lowercase keys (e.g.,
event.headers['content-type']).Exposing a function as a tool
Logic functions can be exposed as tools for AI agents and workflows. When marked as a tool, a function becomes discoverable by Twenty’s AI features and can be used in workflow automations.To mark a logic function as a tool, setisTool: true:src/logic-functions/enrich-company.logic-function.ts
- You can combine
isToolwith triggers — a function can be both a tool (callable by AI agents) and triggered by events at the same time. toolInputSchema(optional): A JSON Schema object describing the parameters your function accepts. The schema is computed automatically from source code static analysis, but you can set it explicitly:
Write a good
description. AI agents rely on the function’s description field to decide when to use the tool. Be specific about what the tool does and when it should be called.definePostInstallLogicFunction
Define a post-install logic function (one per app)
definePostInstallLogicFunction
Define a post-install logic function (one per app)
A post-install function is a logic function that runs automatically once your app has finished installing on a workspace. The server executes it after the app’s metadata has been synchronized and the SDK client has been generated, so the workspace is fully ready to use and the new schema is in place. Typical use cases include seeding default data, creating initial records, configuring workspace settings, or provisioning resources on third-party services.You can also manually execute the post-install function at any time using the CLI:Key points:
src/logic-functions/post-install.ts
- Post-install functions use
definePostInstallLogicFunction()— a specialized variant that omits trigger settings (cronTriggerSettings,databaseEventTriggerSettings,httpRouteTriggerSettings,isTool). - The handler receives an
InstallPayloadwith{ previousVersion?: string; newVersion: string }—newVersionis the version being installed, andpreviousVersionis the version that was previously installed (orundefinedon a fresh install). Use these values to distinguish fresh installs from upgrades and to run version-specific migration logic. - When the hook runs: on fresh installs only, by default. Pass
shouldRunOnVersionUpgrade: trueif you also want it to run when the app is upgraded from a previous version. When omitted, the flag defaults tofalseand upgrades skip the hook. - Execution model — async by default, sync opt-in: the
shouldRunSynchronouslyflag controls how post-install is executed.shouldRunSynchronously: false(default) — the hook is enqueued on the message queue withretryLimit: 3and runs asynchronously in a worker. The install response returns as soon as the job is enqueued, so a slow or failing handler does not block the caller. The worker will retry up to three times. Use this for long-running jobs — seeding large datasets, calling slow third-party APIs, provisioning external resources, anything that might exceed a reasonable HTTP response window.shouldRunSynchronously: true— the hook is executed inline during the install flow (same executor as pre-install). The install request blocks until the handler finishes, and if it throws, the install caller receives aPOST_INSTALL_ERROR. No automatic retries. Use this for fast, must-complete-before-response work — for example, emitting a validation error to the user, or quick setup that the client will rely on immediately after the install call returns. Keep in mind the metadata migration has already been applied by the time post-install runs, so a sync-mode failure does not roll back the schema changes — it only surfaces the error.
- Make sure your handler is idempotent. In async mode the queue may retry up to three times; in either mode the hook may run again on upgrades when
shouldRunOnVersionUpgrade: true. - The environment variables
APPLICATION_ID,APP_ACCESS_TOKEN, andAPI_URLare available inside the handler (same as any other logic function), so you can call the Twenty API with an application access token scoped to your app. - Only one post-install function is allowed per application. The manifest build will error if more than one is detected.
- The function’s
universalIdentifier,shouldRunOnVersionUpgrade, andshouldRunSynchronouslyare automatically attached to the application manifest under thepostInstallLogicFunctionfield during the build — you do not need to reference them indefineApplication(). - The default timeout is set to 300 seconds (5 minutes) to allow for longer setup tasks like data seeding.
- Not executed in dev mode: when an app is registered locally (via
yarn twenty dev), the server skips the install flow entirely and syncs files directly through the CLI watcher — so post-install never runs in dev mode, regardless ofshouldRunSynchronously. Useyarn twenty exec --postInstallto trigger it manually against a running workspace.
definePreInstallLogicFunction
Define a pre-install logic function (one per app)
definePreInstallLogicFunction
Define a pre-install logic function (one per app)
A pre-install function is a logic function that runs automatically during installation, before the workspace metadata migration is applied. It shares the same payload shape as post-install (You can also manually execute the pre-install function at any time using the CLI:Key points:
InstallPayload), but it is positioned earlier in the install flow so it can prepare state that the upcoming migration depends on — typical uses include backing up data, validating compatibility with the new schema, or archiving records that are about to be restructured or dropped.src/logic-functions/pre-install.ts
- Pre-install functions use
definePreInstallLogicFunction()— same specialized config as post-install, just attached to a different lifecycle slot. - Both pre- and post-install handlers receive the same
InstallPayloadtype:{ previousVersion?: string; newVersion: string }. Import it once and reuse it for both hooks. - When the hook runs: positioned just before the workspace metadata migration (
synchronizeFromManifest). Before executing, the server runs a purely additive “pared-down sync” that registers the new version’s pre-install function in the workspace metadata — nothing else is touched — and then executes it. Because this sync is additive-only, the previous version’s objects, fields, and data are still intact when your handler runs: you can safely read and back up pre-migration state. - Execution model: pre-install is executed synchronously and blocks the install. If the handler throws, the install is aborted before any schema changes are applied — the workspace stays on the previous version in a consistent state. This is intentional: pre-install is your last chance to refuse a risky upgrade.
- As with post-install, only one pre-install function is allowed per application. It is attached to the application manifest under
preInstallLogicFunctionautomatically during the build. - Not executed in dev mode: same as post-install — the install flow is skipped entirely for locally-registered apps, so pre-install never runs under
yarn twenty dev. Useyarn twenty exec --preInstallto trigger it manually.
Pre-install vs post-install: when to use which
Choosing the right install hook
Pre-install vs post-install: when to use which
Choosing the right install hook
Both hooks are part of the same install flow and receive the same Pre-install is always synchronous (it blocks the install and can abort it). Post-install is asynchronous by default — enqueued on a worker with automatic retries — but can opt into synchronous execution with Use Rule of thumb:
InstallPayload. The difference is when they run relative to the workspace metadata migration, and that changes what data they can safely touch.shouldRunSynchronously: true. See the definePostInstallLogicFunction accordion above for when to use each mode.Use post-install for anything that needs the new schema to exist. This is the common case:- Seeding default data (creating initial records, default views, demo content) against newly-added objects and fields.
- Registering webhooks with third-party services now that the app has its credentials.
- Calling your own API to finish setup that depends on the synchronized metadata.
- Idempotent “ensure this exists” logic that should reconcile state on every upgrade — combine with
shouldRunOnVersionUpgrade: true.
PostCard record after install:src/logic-functions/post-install.ts
pre-install when a migration would otherwise destroy or corrupt existing data. Because pre-install runs against the previous schema and its failure rolls back the upgrade, it is the right place for anything risky:- Backing up data that is about to be dropped or restructured — e.g. you are removing a field in v2 and need to copy its values into another field or export them to storage before the migration runs.
- Archiving records that a new constraint would invalidate — e.g. a field is becoming
NOT NULLand you need to delete or fix rows with null values first. - Validating compatibility and refusing the upgrade if the current data cannot be migrated cleanly — throw from the handler and the install aborts with no changes applied. This is safer than discovering the incompatibility mid-migration.
- Renaming or rekeying data ahead of a schema change that would lose the association.
src/logic-functions/pre-install.ts
| You want to… | Use |
|---|---|
| Seed default data, configure the workspace, register external resources | post-install |
| Run long-running seeding or third-party calls that shouldn’t block the install response | post-install (default — shouldRunSynchronously: false, with worker retries) |
| Run fast setup that the caller will rely on immediately after the install call returns | post-install with shouldRunSynchronously: true |
| Read or back up data that the upcoming migration would lose | pre-install |
| Reject an upgrade that would corrupt existing data | pre-install (throw from the handler) |
| Run reconciliation on every upgrade | post-install with shouldRunOnVersionUpgrade: true |
| Do one-off setup on the first install only | post-install with shouldRunOnVersionUpgrade: false (default) |
If in doubt, default to post-install. Only reach for pre-install when the migration itself is destructive and you need to intercept the previous state before it is gone.
Typed API clients (twenty-client-sdk)
Thetwenty-client-sdk package provides two typed GraphQL clients for interacting with the Twenty API from your logic functions and front components.
| Client | Import | Endpoint | Generated? |
|---|---|---|---|
CoreApiClient | twenty-client-sdk/core | /graphql — workspace data (records, objects) | Yes, at dev/build time |
MetadataApiClient | twenty-client-sdk/metadata | /metadata — workspace config, file uploads | No, ships pre-built |
CoreApiClient
Query and mutate workspace data (records, objects)
CoreApiClient
Query and mutate workspace data (records, objects)
CoreApiClient is the main client for querying and mutating workspace data. It is generated from your workspace schema during yarn twenty dev or yarn twenty build, so it is fully typed to match your objects and fields.true to include a field, use __args for arguments, and nest objects for relations. You get full autocompletion and type checking based on your workspace schema.CoreApiClient is generated at dev/build time. If you use it without running
yarn twenty dev or yarn twenty build first, it throws an error. The generation happens automatically — the CLI introspects your workspace’s GraphQL schema and generates a typed client using @genql/cli.Using CoreSchema for type annotations
CoreSchema provides TypeScript types matching your workspace objects — useful for typing component state or function parameters:MetadataApiClient
Workspace config, applications, and file uploads
MetadataApiClient
Workspace config, applications, and file uploads
MetadataApiClient ships pre-built with the SDK (no generation required). It queries the /metadata endpoint for workspace configuration, applications, and file uploads.Uploading files
MetadataApiClient includes an uploadFile method for attaching files to file-type fields:| Parameter | Type | Description |
|---|---|---|
fileBuffer | Buffer | The raw file contents |
filename | string | The name of the file (used for storage and display) |
contentType | string | MIME type (defaults to application/octet-stream if omitted) |
fieldMetadataUniversalIdentifier | string | The universalIdentifier of the file-type field on your object |
- Uses the field’s
universalIdentifier(not its workspace-specific ID), so your upload code works across any workspace where your app is installed. - The returned
urlis a signed URL you can use to access the uploaded file.
When your code runs on Twenty (logic functions or front components), the platform injects credentials as environment variables:
TWENTY_API_URL— Base URL of the Twenty APITWENTY_APP_ACCESS_TOKEN— Short-lived key scoped to your application’s default function role
process.env automatically. The API key’s permissions are determined by the role referenced in defaultRoleUniversalIdentifier in your application-config.ts.