Overview
Logic functions are server-side TypeScript functions that run on the Twenty platform. They can be triggered by HTTP requests, cron schedules, or database events — and can also be exposed as tools for AI agents.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:On the workspace host (A sandboxed page keeps scripts, forms, popups, modals and downloads, but runs with an opaque origin: The endpoint is reachable at:The first segment is your app registration’s id, the second the resolver’s Answering a verification GET. Some providers verify an endpoint before they deliver to it, by sending a The challenge arrives in Resolver contract. The SDK’s The payload includes:Created event example:Updated event example:Trigger only on email updates:Trigger only when an opportunity moves to the customer stage:Destroyed event example:The handler then receives a Events are grouped by the user who caused them before being batched, so every call covers a single actor and Build both once, at module scope, and every call site then says which access it uses by which client it calls. The SDK helpers that reach your application’s own resources always use its access and ignore Key points:To declare your parameters once and serve both surfaces, define a single JSON Schema (The component reads the call it is rendering with The component mounts as soon as the agent has finished streaming its arguments, so it owns the whole call, not just the result. Both Once the app is installed, Enrich Company appears in the workflow builder’s action picker. The builder renders
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. In app code, prefix the route path with
/s/when usingRestApiClient; the deployed URL uses the injectedTWENTY_FUNCTIONS_URLbase (or<server-url>/swhen it is not set).
To invoke a route-triggered logic function from a (headless) front component, see Calling a logic function.
- cron: Runs your function on a schedule using a CRON expression. Set
spreadMsto keep every workspace from running it at the same minute. See Spread a cron across workspaces. - databaseEvent: Runs when records of an object are created, updated, deleted, destroyed, restored or upserted. You can limit it to updates of some fields and to records that meet a condition. See Database event payloads.
- serverRoute: Exposes a single registration-scoped HTTP route. A resolver function (declared with
serverRouteTriggerSettings) runs in the owner workspace and either returns a syncResponseor the target workspace AND logic function to enqueue; on the enqueue path the platform acks with202and runs that target on the worker queue. See Server route trigger.
You can also manually execute a function using the CLI:You can watch logs with:
On the cloud, each run consumes workspace credits: a flat charge per
invocation plus a per-millisecond charge for the time the function runs, so
keeping
timeoutSeconds tight and code fast keeps costs down. See
Credits for the rates.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/logic-function:RoutePayload type has the following structure: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']).Custom HTTP response
By default, returning a plain value from your handler sends it back as a200 response (JSON for objects, text/plain for strings). To control the status code and response headers, return a Response from twenty-sdk/logic-function:/s/) and on server routes, response headers are restricted to an allow-list for security reasons. Any header that is not on the list (e.g. Set-Cookie, CORS headers such as Access-Control-Allow-Origin, or custom X-* headers) is silently dropped before the response is sent. On a public domain, every header is kept. The allowed response headers are:content-typecontent-languagecontent-dispositioncache-controlretry-after
The status code must be a valid HTTP status code (between 100 and 599).
Response header names are matched case-insensitively.
Where route pages run
Every route response carriesX-Content-Type-Options: nosniff, so a route loaded as a script or stylesheet must declare a JavaScript or CSS content type. Most also carry a sandbox policy, which isolates the pages your routes return from the Twenty app and from other applications:document.cookie, localStorage and sessionStorage throw, and its requests, even to your own routes, are cross-origin. Browser libraries that need a real origin, such as Stripe.js, do not work there.A custom domain belongs to one application. Register it in Settings → Applications → your application → Custom Domain, add the DNS records shown there and wait until it is validated. From then on,
TWENTY_FUNCTIONS_URL points at it (the oldest validated one when there are several), so links built with RestApiClient or resolveUrl use that domain.Custom domains are validated through Cloudflare. On an instance without
Cloudflare configured, a custom domain serves routes as soon as its
core.publicDomain row exists.Platform error responses
Beyond your handler’s own responses, the platform answers route calls directly in some situations:404 when the route or function does not exist, 403 when the application is stopped, 402 when the workspace has exhausted its credit allowance or has no active subscription, 409 when a storage limit is reached, 429 when an execution rate limit or a usage limit is hit, and 422 when the application’s production dependencies are too large to install — see dependencies size limits.Server route trigger
httpRouteTriggerSettings exposes a function under /s/ and resolves the workspace from the request host — which works when each workspace has its own domain. Third-party providers, however, deliver every tenant’s events to one URL. For that case, use serverRouteTriggerSettings.The trigger has two parts:-
A resolver logic function — declared with
serverRouteTriggerSettings— runs in your owner workspace (the workspace that owns the application registration). It inspects the incoming request and returns either:{ workspaceId, targetLogicFunctionUniversalIdentifier, payload? }— the platform enqueues that target in the resolved workspace and acks with202 { queued: true }, or- a
Responsefromtwenty-sdk/logic-function— the platform echoes that HTTP response synchronously and does not enqueue a target (use this for challenge handshakes such as Slackurl_verification).
rawBodyand forwarded headers, and can reject without ever touching the target. - A target logic function — a regular per-workspace logic function — then runs in the resolved workspace with the payload returned by the resolver (or the original request payload if the resolver didn’t transform it). Its return value is not observed by the HTTP caller when the resolver chose the enqueue path.
src/logic-functions/resolve-server-route.logic-function.ts
src/logic-functions/handle-invoice-paid.logic-function.ts
universalIdentifier from your manifest. A route only resolves to a resolver of that registration, in its owner workspace. When your app registers the webhook itself, build the URL from inside a logic function with getServerRouteUrl; Twenty injects the base URL of your app’s server routes as TWENTY_SERVER_ROUTES_URL:URLs carrying only the resolver’s
id or universalIdentifier
(/webhooks/server/:identifier) still resolve for now, and both answer with
a Deprecation header. The universalIdentifier form returns 409 when two
registrations declare the same identifier. Move the URLs registered with your
providers to the registration form.GET carrying a challenge to the same URL they will later POST events to — Meta’s WhatsApp Cloud API is one. A server route answers POST only unless you say otherwise, so declare both methods:event.queryStringParameters, and returning a Response echoes it back to the provider on the same request. A string body is sent as text/plain, which is what these providers expect:httpMethods replaces the default rather than adding to it, so ['GET'] alone makes the route reject POST. Only GET and POST are supported. Leave it unset unless the provider needs the second verb: a route that declares GET will have its resolver executed by any unauthenticated caller, including the crawlers and link unfurlers that send GET unprompted. Anything the platform does not have a method for is answered 405 without the resolver ever running.The application must be claimed and installed on its owner workspace.
Follow Claiming your
app to
assign an owner, then install the app in that workspace. Until both are true,
the resolver has nowhere to run and the server route returns
404
(LOGIC_FUNCTION_NOT_FOUND), even if the app is installed elsewhere.
Marketplace search hides apps with server routes until this setup and all
required server variables are complete. See owner workspace costs and
availability
for billing and operational details.LogicFunctionConfig type enforces this at compile time: as soon as you set serverRouteTriggerSettings, your handler is constrained to return either a Response, or { workspaceId: string; targetLogicFunctionUniversalIdentifier: string; payload?: object } (or a Promise of either). On the dispatch path, if the app is not installed in the workspaceId, nothing runs and the request is acknowledged with 200 and { queued: false, reason: "APPLICATION_NOT_INSTALLED" }, so the provider stops redelivering an event no workspace can process. If the app is installed there but has no function with that targetLogicFunctionUniversalIdentifier, the request is rejected with 404. A result that matches neither shape — including one whose identifiers are not UUIDs — is rejected with 502.Bearer tokens. Some providers, such as Microsoft Bot Framework, sign each request with a JWT in the
Authorization header instead of a signature header. A server route can list authorization in forwardedRequestHeaders to receive it, and the resolver verifies it like any other signature. The platform removes the header if it carries a token issued by Twenty, so a server route never receives a Twenty session. cookie and proxy-authorization are never forwarded, and HTTP routes cannot forward any of these three headers.For request signatures, most providers sign with HMAC-SHA256; the parts that differ are the header name, the digest encoding, and the signed-payload string. A few examples:The resolver example above already shows the GitHub HMAC-SHA256 flow — adapt the header name, digest encoding, and signed-payload string per the provider you’re integrating.
When the resolver returns a dispatch object, the route responds
202 { queued: true } and the target runs on the worker queue — the caller never observes the target’s latency, result, or failures (those are recorded in execution logs). This keeps sender redeliveries from amplifying processing slowdowns, which is what you want for webhook ingestion.The resolver runs in the owner workspace and spends its credits, so the route answers 402 when that workspace has exhausted its allowance or has no active subscription, and 429 when a usage limit is hit. Senders that retry on 5xx will not retry these, which is what you want: the refusal will not clear on the next attempt.When the caller must read the response body on the same request (challenge handshakes, interactive acknowledgements), return a Response from the resolver instead. The platform echoes it synchronously and skips the queue; its headers go through the same allow-list as HTTP route responses. Keep the resolver fast — some providers (e.g. Slack) time out in a few seconds. Because the resolver is reachable as a public endpoint, protect it with rate limiting at your edge.Database event trigger payload
When a database event trigger invokes your logic function, it receives oneDatabaseEventPayload per changed record (or a DatabaseEventBatchPayload covering several records when batchMode is enabled). The payload combines metadata about the source workspace and object with the record-level event.For soft deletes,
.deleted follows the update-style shape because the record’s deletedAt field changes.
For permanent deletes, use .destroyed.eventTriggerSettings.watchedFieldUniversalIdentifiers filters which update
events trigger the function. event.properties.updatedFields tells you which fields
actually changed on the current event.eventTriggerSettings with on: 'recordEvent' accepts:The build fails when an object or field is unknown, or when the condition reads a field the object does not have. A condition reads the record the way the API returns it, like a validation rule:
company.id for the related company, company.employees > 100 for one of its fields. Related fields are read when the event is dispatched, with the application’s permissions, so a related record the application cannot read counts as empty. previous. only covers the record’s own fields.The earlier
databaseEventTriggerSettings, with eventName (such as
person.updated or *.created) and updatedFields (field names), is still
accepted, but will be removed in a future release. Set one of the two, not both.Batching database events
A bulk write emits many events at once: importing a mailbox, for instance, can update thousands of records in a single operation, and one call per record floods the queue. SetbatchMode to receive them together:DatabaseEventBatchPayload, which carries the same metadata as DatabaseEventPayload but replaces the record-level fields with an events array:Batch size is not something a handler can rely on. The server decides how many
events a call carries, capped at 200, and a batch holds anything from a single
event up to that ceiling depending on how many the originating write produced.
Write the handler to loop over
events whatever its length.context.workspaceMemberId stays meaningful. Field and condition filtering are applied before batching, so a batch only contains records you asked for.Without batchMode, the handler keeps receiving one DatabaseEventPayload per record.Execution context
Generic logic function handlers receive a second argument describing the run itself, whatever triggered it. Where the first argument changes shape per trigger, this one does not:userWorkspaceId and workspaceMemberId are null when nobody triggered the run: cron schedules, install hooks and unauthenticated webhooks have no person behind them. They are also null when the person has no workspace member record, or theirs has been deleted.The context tells you who triggered the run. What the run may do is a
separate declaration, below.
Whose access a call uses
Every client —CoreApiClient, MetadataApiClient and RestApiClient — acts as the person who triggered the run: their role intersected with your application’s, so the call can never do more than either of you. That is the default, and it means a person can never use your app to exceed their own permissions.When nobody triggered the run there is no person to act as, so the same client falls back to your application’s own access: cron schedules, install hooks and unauthenticated webhooks need no special handling.Some calls legitimately need the application’s own access even when a person is behind the run — reading your app’s configuration records, or doing work that person could not do themselves. Build a second client for those:RestApiClient takes the same option:A run nobody triggered acts as your application. Cron schedules, install hooks and unauthenticated webhooks have no person behind them, so the default client falls back to your application’s own access and keeps working.
runAs: 'application' is only needed when you want that access in a run a person did trigger.Check context.workspaceMemberId when a function behaves differently depending on whether someone is behind it, for instance to attribute a record.runAs: the key-value store, connections, messaging channels, runAgent, getPublicAssetUrl and credit charging. ai.generate follows the default clients instead: it acts as the person who triggered the run, within your app’s role, or as your app when nobody did.Exposing a function as an AI tool or workflow action
Logic functions can be exposed on two surfaces, each with its own trigger:toolTriggerSettings— makes the function discoverable by Twenty’s AI features (chat, MCP, function calling). Uses standard JSON Schema, the format LLMs natively understand.workflowActionTriggerSettings— makes the function appear as a step in the visual workflow builder. Uses Twenty’s richInputSchemaso the builder can render proper field editors, variable pickers, and labels.
cronTriggerSettings, eventTriggerSettings, and httpRouteTriggerSettings — same pattern, same shape.Relationship to the workflow Code action. The built-in Code action in
the workflow builder is itself a logic function — Twenty creates one per Code
step and exposes its editor inline.
workflowActionTriggerSettings is how you
turn that one-off, inline code into a reusable action: define the function
once in your app and it becomes selectable in any workflow, instead of being
copy-pasted into each Code step. See the Code
action in the user
guide for the end-user view.src/logic-functions/enrich-company.logic-function.ts
- A function can mix surfaces — declare both
toolTriggerSettingsandworkflowActionTriggerSettingsto expose it in chat AND in the workflow builder. toolTriggerSettings.inputSchemaandworkflowActionTriggerSettings.inputSchemaare both optional. When omitted, the manifest builder infers them from the handler source code (JSON Schema for the AI tool, Twenty’sInputSchemafor the workflow action). Provide one explicitly when you want richer typing — for example, withFieldMetadataType-aware fields likeCURRENCYorRELATIONfor the workflow builder, or withdescriptionfields the AI agent can read:
InputJsonSchema) and convert it for the workflow action with jsonSchemaToInputSchema from twenty-sdk/logic-function. toolTriggerSettings.inputSchema takes the JSON Schema directly, while workflowActionTriggerSettings.inputSchema expects Twenty’s InputSchema:Rendering a tool call with a front component
By default a tool call shows up in the AI chat as a step row: the tool’s name, and a spinner until it returns. PointtoolTriggerSettings.frontComponentUniversalIdentifier at one of your front components and the chat renders that component inline instead, for every call to this tool.useToolCall():src/front-components/invoice-preview.tsx
toolCall.status walks through input-available, the approval states when the tool needs one, and then output-available, output-denied or output-error; input is what the agent proposed, output what your handler returned. Render each state you care about, since the step row is no longer there to cover them.When the agent proposes a call that waits for a person’s approval, the approval card shows the same component in place of the raw JSON arguments. The card keeps its header, Reject and Approve. While toolCall.status is approval-requested, input holds the arguments Approve will submit, and the component can change them with setToolCallArguments:input and output are typed Record<string, unknown>, so narrow each field before you use it rather than casting. That matters most for anything you hand to the DOM: a value you drop into an href without checking it is a string is a link the tool’s output controls.If the identifier matches no front component in the app, the chat falls back
to the default step row. Front components in the AI chat run under the same
role your app declares, so a widget
can only read and write what the app itself is allowed to.
A complete workflow action example
workflowActionTriggerSettings accepts four fields:Putting it together — a function exposed as a workflow action, with a declared output so later steps can reference
taskId:src/logic-functions/enrich-company.logic-function.ts
companyName and domain as input fields (each able to pull values from previous steps), and downstream steps can reference the step’s taskId and enriched outputs.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.Runtime helpers.
twenty-sdk/utils re-exports small runtime helpers so handlers never import from twenty-shared directly. For example, isDefined(value) returns false for both null and undefined — use it to safely narrow optional handler inputs, which can arrive as null at runtime even when typed T | undefined:Work addresses. The domain is compared as written, so lowercase the address first.
isWorkEmail(address) from twenty-sdk/email tells a company address from a personal one, with the same list of free and disposable email providers Twenty itself uses. It has its own entry because that list weighs about 240 KB, so only the functions that import it bundle it:Install hooks — pre-install, post-install, and uninstall handlers — share
this runtime but are declared with their own define functions and don’t take
trigger settings. See Install
Hooks for
definePreInstallLogicFunction, definePostInstallLogicFunction, and
defineUninstallLogicFunction.Health check
Declare a health check withdefineHealthCheck to report whether your app is actually able to run. It is for what only the app can know: a key that is present but revoked, an account on the wrong plan, a webhook that was never registered. What Twenty can see by itself — a required variable nobody filled in — is covered by isRequired and needs no code.
It runs server-side, so it reads secret variables like any other logic function. A workspace check has nobody behind it, so the handler needs no arguments.
src/logic-functions/health-check.ts
OK shows no banner at all; every other status renders the title in a banner coloured after it, so pick the one that matches how much the person needs to act. The statuses are Twenty’s own ApplicationHealthStatus, so the plain string and the enum member are interchangeable:
/ or #: an external, protocol-relative or relative one loses its button rather than becoming a redirect somewhere else. The button is also dropped when the app reports no location and has no configuration tab to fall back to, so a check on an app with no variables and no settings menu items shows its title without a dead button.
Checking each member’s own setup
An app declares one health-check function. OmitrunOnUserPreferences or set it to false to run a workspace check on the app’s settings page, with a zero-argument handler. Set runOnUserPreferences: true to run a member check on their Apps preferences page instead. A member handler receives the required { userWorkspaceId: string } from the authenticated session:
src/logic-functions/health-check.ts
{ userWorkspaceId } from the authenticated session, and user-scoped variables hold their values. The parameter object and ID are required for this mode. It does not run on workspace app settings. Pass userWorkspaceId to listConnections() so it returns that member’s connections only. A connection whose token refresh fails is left out of the list, so “no connection” covers “reconnect” too. A button with no location lands on the app’s General tab of that page.
Member checks require Twenty 2.55.0 or later. Apps preferences is not enabled
in every workspace yet: where it is not, a member check never runs.
Create a timeline activity
UsecreateTimelineActivity() to publish an explicit domain event from a logic function. Define the event first as a timeline activity type, then address the type and objects by their stable universal identifiers:
timelineActivityTypeUniversalIdentifier, targetObjectUniversalIdentifier, and targetRecordId. You can also provide happensAt, properties, and workspaceMemberId. happensAt controls the event’s position and displayed time in the timeline; it defaults to the creation time.
To associate another record with the event, provide linkedRecordId and linkedObjectMetadataUniversalIdentifier together. You can additionally provide linkedRecordCachedName as a historical display fallback:
timelineActivity object. Keep explicit event types unbound from an action; an action-bound type already receives automatic audit events and would otherwise produce duplicate rows.
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.
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 with twenty app generate-client, or after a sync with twenty app apply or twenty app dev, so it is fully typed to match your objects and fields.shareWith only matters on an object whose records are private; elsewhere the argument is ignored. On such an object it lists who gets access to the created record: each entry targets exactly one of workspaceMemberId, roleId or everyone: true with an accessLevel of READ, READ_WRITE or FULL. A workspace member creating a record always receives a FULL owner grant, so the argument is optional for them; a logic function acting as its application or an API key also receives a FULL grant for its role, and such callers, like a system caller, must pass shareWith or the create is rejected. Every entry must name a member or a role of the workspace. A logic function or API key shares through its role, so every holder of that role gets the same access to the records it creates; give a key whose records must stay private to it a role of its own.The client uses a selection-set syntax: pass 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.Run
twenty app generate-client to refresh the client from your workspace’s
GraphQL schema. twenty app apply and twenty app dev also regenerate it
after syncing. twenty app build only builds locally and does not generate
the client.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. It takes the same runAs option as CoreApiClient — see Whose access a call uses.It is also how an app reads and updates its own application variables, in a logic function as in a front component. An application token only ever reaches its own application, in its own workspace.A user variable is in process.env with the value of the member who triggered the run, or its default until they set their own. A run nobody triggered gets no user variables. To read every member’s value of your app’s user variables, for example in a cron job, query myUserApplicationVariables with runAs: 'application'.Uploading files
MetadataApiClient includes an uploadFile method for attaching files to file-type fields. The file goes straight to Twenty’s file storage: the API issues an upload target, the client sends the bytes there, then the API confirms the upload.Key points:
- Uses the field’s
universalIdentifier(not its workspace-specific ID), so your upload code works across any workspace where your app is installed. - The MIME type is detected from the file contents once uploaded, so there is nothing to declare.
- 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_INTERNAL_API_URL: private address of Twenty. Logic functions only, and only when the operator setsSERVER_INTERNAL_URL, for example behind an authenticating proxy. The clients use it automatically,RestApiClient.resolveUrlincluded. If you call the API yourself, use it when set and fall back toTWENTY_API_URL. Build links you hand to browsers or other services, such as webhook URLs, fromTWENTY_API_URLorgetServerRouteUrl.TWENTY_APP_ACCESS_TOKEN— Short-lived key for the default access: a person’s role intersected with your application’s when someone is behind the run, your application’s own role when nobody is. The person is whoever triggered the run in a logic function, whoever is looking at the page in a front component.TWENTY_APP_APPLICATION_ACCESS_TOKEN— Short-lived key scoped to your application’s own role alone. Logic functions only, always injected there, and whatrunAs: 'application'uses.
process.env automatically, and Whose access a call uses covers picking between them. Your application’s own permissions are determined by the role declared with defineApplicationRole() (or referenced via defaultRoleUniversalIdentifier in application-config.ts); a run acting as a person can never exceed that role, nor theirs.Spread a cron across workspaces
A cron pattern matches at the same minute in every workspace that installed your app. AddspreadMs to shift each workspace’s runs by its own offset:
[0, spreadMs), rounded down to the minute and derived from the workspace and the function’s universalIdentifier, so it stays the same from one run to the next. The pattern is evaluated that much later in the workspace: with the example above, a workspace with a 37 minute offset runs at 03:37 every day.
spreadMsis an integer between120000(2 minutes) and86400000(24 hours).- The offset shifts when the cron runs, not how often. A cron that runs every minute still runs every minute, and an hourly cron with a 24 hour
spreadMsstill runs once an hour in each workspace. - There is no minimum gap between workspaces and no cap on how many run in the same minute: offsets are spread, not coordinated.
- Changing
spreadMschanges the offset, so the run around the change can be skipped or happen twice. - Without
spreadMs, the cron runs at the minute its pattern matches.