Use the SDK resources (types & config)
The twenty-sdk provides typed building blocks and helper functions you use inside your app. Below are the key pieces you’ll touch most often.Helper functions
The SDK provides helper functions for defining your app entities. As described in Entity detection, you must useexport default define<Entity>({...}) for your entities to be detected:
| Function | Purpose |
|---|---|
defineApplication | Configure application metadata (required, one per app) |
defineObject | Define custom objects with fields |
defineLogicFunction | Define logic functions with handlers |
definePreInstallLogicFunction | Define a pre-install logic function (one per app) |
definePostInstallLogicFunction | Define a post-install logic function (one per app) |
defineFrontComponent | Define front components for custom UI |
defineRole | Configure role permissions and object access |
defineField | Extend existing objects with additional fields |
defineView | Define saved views for objects |
defineNavigationMenuItem | Define sidebar navigation links |
defineSkill | Define AI agent skills |
Defining objects
Custom objects describe both schema and behavior for records in your workspace. UsedefineObject() to define objects with built-in validation:
- Use
defineObject()for built-in validation and better IDE support. - The
universalIdentifiermust be unique and stable across deployments. - Each field requires a
name,type,label, and its own stableuniversalIdentifier. - The
fieldsarray is optional — you can define objects without custom fields. - You can scaffold new objects using
yarn twenty entity:add, which guides you through naming, fields, and relationships.
Base fields are created automatically. When you define a custom object, Twenty automatically adds standard fields
such as
id, name, createdAt, updatedAt, createdBy, updatedBy and deletedAt.
You don’t need to define these in your fields array — only add your custom fields.
You can override default fields by defining a field with the same name in your fields array,
but this is not recommended.Application config (application-config.ts)
Every app has a singleapplication-config.ts file that describes:
- Who the app is: identifiers, display name, and description.
- How its functions run: which role they use for permissions.
- (Optional) variables: key–value pairs exposed to your functions as environment variables.
- (Optional) pre-install function: a logic function that runs before the app is installed.
- (Optional) post-install function: a logic function that runs after the app is installed.
defineApplication() to define your application configuration:
universalIdentifierfields are deterministic IDs you own; generate them once and keep them stable across syncs.applicationVariablesbecome environment variables for your functions (for example,DEFAULT_RECIPIENT_NAMEis available asprocess.env.DEFAULT_RECIPIENT_NAME).defaultRoleUniversalIdentifiermust match the role file (see below).- Pre-install and post-install functions are automatically detected during the manifest build. See Pre-install functions and Post-install functions.
Roles and permissions
Applications can define roles that encapsulate permissions on your workspace’s objects and actions. The fielddefaultRoleUniversalIdentifier in application-config.ts designates the default role used by your app’s logic functions.
- The runtime API key injected as
TWENTY_API_KEYis derived from this default function role. - The typed client will be restricted to the permissions granted to that role.
- Follow least‑privilege: create a dedicated role with only the permissions your functions need, then reference its universal identifier.
Default function role (*.role.ts)
When you scaffold a new app, the CLI also creates a default role file. UsedefineRole() to define roles with built-in validation:
universalIdentifier of this role is then referenced in application-config.ts as defaultRoleUniversalIdentifier. In other words:
- *.role.ts defines what the default function role can do.
- application-config.ts points to that role so your functions inherit its permissions.
- Start from the scaffolded role, then progressively restrict it following least‑privilege.
- Replace the
objectPermissionsandfieldPermissionswith the objects/fields your functions need. permissionFlagscontrol access to platform-level capabilities. Keep them minimal; add only what you need.- See a working example in the Hello World app:
packages/twenty-apps/hello-world/src/roles/function-role.ts.
Logic function config and entrypoint
Each function file usesdefineLogicFunction() to export a configuration with a handler and optional triggers.
- route: Exposes your function on an HTTP path and method under the
/s/endpoint:
e.g.path: '/post-card/create',-> call on<APP_URL>/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
Notes:
- The
triggersarray is optional. Functions without triggers can be used as utility functions called by other functions. - You can mix multiple trigger types in a single function.
Pre-install functions
A pre-install function is a logic function that runs automatically before your app is installed on a workspace. This is useful for validation tasks, prerequisite checks, or preparing workspace state before the main installation proceeds. When you scaffold a new app withcreate-twenty-app, a pre-install function is generated for you at src/logic-functions/pre-install.ts:
- Pre-install functions use
definePreInstallLogicFunction()— a specialized variant that omits trigger settings (cronTriggerSettings,databaseEventTriggerSettings,httpRouteTriggerSettings,isTool). - The handler receives an
InstallLogicFunctionPayloadwith{ previousVersion: string }— the version of the app that was previously installed (or an empty string for fresh installs). - Only one pre-install function is allowed per application. The manifest build will error if more than one is detected.
- The function’s
universalIdentifieris automatically set aspreInstallLogicFunctionUniversalIdentifieron the application manifest during the build — you do not need to reference it indefineApplication(). - The default timeout is set to 300 seconds (5 minutes) to allow for longer preparation tasks.
- Pre-install functions do not need triggers — they are invoked by the platform before installation or manually via
function:execute --preInstall.
Post-install functions
A post-install function is a logic function that runs automatically after your app is installed on a workspace. This is useful for one-time setup tasks such as seeding default data, creating initial records, or configuring workspace settings. When you scaffold a new app withcreate-twenty-app, a post-install function is generated for you at 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
InstallLogicFunctionPayloadwith{ previousVersion: string }— the version of the app that was previously installed (or an empty string for fresh installs). - Only one post-install function is allowed per application. The manifest build will error if more than one is detected.
- The function’s
universalIdentifieris automatically set aspostInstallLogicFunctionUniversalIdentifieron the application manifest during the build — you do not need to reference it indefineApplication(). - The default timeout is set to 300 seconds (5 minutes) to allow for longer setup tasks like data seeding.
- Post-install functions do not need triggers — they are invoked by the platform during installation or manually via
function:execute --postInstall.
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 type from twenty-sdk:
RoutePayload type has the following structure:
| Property | Type | Description |
|---|---|---|
headers | Record<string, string | undefined> | HTTP headers (only those listed in forwardedRequestHeaders) |
queryStringParameters | Record<string, string | undefined> | Query string parameters (multiple values joined with commas) |
pathParameters | Record<string, string | undefined> | Path parameters extracted from the route pattern (e.g., /users/:id → { id: '123' }) |
body | object | null | Parsed request body (JSON) |
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 |
Forwarding HTTP headers
By default, HTTP headers from incoming requests are not passed to your logic function for security reasons. To access specific headers, explicitly list them in theforwardedRequestHeaders array:
Header names are normalized to lowercase. Access them using lowercase keys (for example,
event.headers['content-type']).- Scaffolded: Run
yarn twenty entity:addand choose the option to add a new logic function. This generates a starter file with a handler and config. - Manual: Create a new
*.logic-function.tsfile and usedefineLogicFunction(), following the same pattern.
Marking a logic function as a tool
Logic functions can be exposed as tools for AI agents and workflows. When a function is marked as a tool, it becomes discoverable by Twenty’s AI features and can be selected as a step in workflow automations. To mark a logic function as a tool, setisTool: true and provide a toolInputSchema describing the expected input parameters using JSON Schema:
isTool(boolean, default:false): When set totrue, the function is registered as a tool and becomes available to AI agents and workflow automations.toolInputSchema(object, optional): A JSON Schema object that describes the parameters your function accepts. AI agents use this schema to understand what inputs the tool expects and to validate calls. If omitted, the schema defaults to{ type: 'object', properties: {} }(no parameters).- Functions with
isTool: false(or unset) are not exposed as tools. They can still be executed directly or called by other functions, but will not appear in tool discovery. - Tool naming: When exposed as a tool, the function name is automatically normalized to
logic_function_<name>(lowercased, non-alphanumeric characters replaced with underscores). For example,enrich-companybecomeslogic_function_enrich_company. - You can combine
isToolwith triggers — a function can be both a tool (callable by AI agents) and triggered by events (cron, database events, routes) at the same time.
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.Front components
Front components let you build custom React components that render within Twenty’s UI. UsedefineFrontComponent() to define components with built-in validation:
- Front components are React components that render in isolated contexts within Twenty.
- The
componentfield references your React component. - Components are built and synced automatically during
yarn twenty app:dev.
- Scaffolded: Run
yarn twenty entity:addand choose the option to add a new front component. - Manual: Create a new
.tsxfile and usedefineFrontComponent(), following the same pattern.
Skills
Skills define reusable instructions and capabilities that AI agents can use within your workspace. UsedefineSkill() to define skills with built-in validation:
nameis a unique identifier string for the skill (kebab-case recommended).labelis the human-readable display name shown in the UI.contentcontains the skill instructions — this is the text the AI agent uses.icon(optional) sets the icon displayed in the UI.description(optional) provides additional context about the skill’s purpose.
- Scaffolded: Run
yarn twenty entity:addand choose the option to add a new skill. - Manual: Create a new file and use
defineSkill(), following the same pattern.
Generated typed clients
Two typed clients are auto-generated byyarn twenty app:dev and stored in node_modules/twenty-sdk/generated based on your workspace schema:
CoreApiClient— queries the/graphqlendpoint for workspace dataMetadataApiClient— queries the/metadataendpoint for workspace configuration and file uploads
yarn twenty app:dev whenever your objects or fields change.
Runtime credentials in logic functions
When your function runs on Twenty, the platform injects credentials as environment variables before your code executes:TWENTY_API_URL: Base URL of the Twenty API your app targets.TWENTY_API_KEY: Short‑lived key scoped to your application’s default function role.
- You do not need to pass URL or API key to the generated client. It reads
TWENTY_API_URLandTWENTY_API_KEYfrom process.env at runtime. - The API key’s permissions are determined by the role referenced in your
application-config.tsviadefaultRoleUniversalIdentifier. This is the default role used by logic functions of your application. - Applications can define roles to follow least‑privilege. Grant only the permissions your functions need, then point
defaultRoleUniversalIdentifierto that role’s universal identifier.
Uploading files
The generatedMetadataApiClient includes an uploadFile method for attaching files to file-type fields on your workspace objects. Because standard GraphQL clients do not support multipart file uploads natively, the client provides this dedicated method that implements the GraphQL multipart request specification under the hood.
| 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 of the file (defaults to application/octet-stream if omitted) |
fieldMetadataUniversalIdentifier | string | The universalIdentifier of the file-type field on your object |
- The
uploadFilemethod is available onMetadataApiClientbecause the upload mutation is resolved by the/metadataendpoint. - It uses the field’s
universalIdentifier(not its workspace-specific ID), so your upload code works across any workspace where your app is installed — consistent with how apps reference fields everywhere else. - The returned
urlis a signed URL you can use to access the uploaded file.