Skip to content

The open alternative to Salesforce, designed for AI.

2474 add a utils to perform route trigger logic function requests in front components (#21330)

martmull27aea728df32
diff --git a/packages/twenty-client-sdk/package.json b/packages/twenty-client-sdk/package.json
index 2cc55565cd3..5c3c40f0a83 100644
--- a/packages/twenty-client-sdk/package.json
+++ b/packages/twenty-client-sdk/package.json
@@ -17,6 +17,11 @@
"import": "./dist/metadata.mjs",
"require": "./dist/metadata.cjs"
},
+ "./rest": {
+ "types": "./dist/rest/index.d.ts",
+ "import": "./dist/rest.mjs",
+ "require": "./dist/rest.cjs"
+ },
"./generate": {
"types": "./dist/generate/index.d.ts",
"import": "./dist/generate.mjs",
@@ -31,6 +36,9 @@
"metadata": [
"dist/metadata/index.d.ts"
],
+ "rest": [
+ "dist/rest/index.d.ts"
+ ],
"generate": [
"dist/generate/index.d.ts"
]
diff --git a/packages/twenty-client-sdk/src/rest/__tests__/RestApiClient.test.ts b/packages/twenty-client-sdk/src/rest/__tests__/RestApiClient.test.ts
new file mode 100644
index 00000000000..efc158a8608
--- /dev/null
+++ b/packages/twenty-client-sdk/src/rest/__tests__/RestApiClient.test.ts
@@ -0,0 +1,151 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { RestApiClient, RestApiClientError } from '../index';
+
+const buildResponse = (
+ body: string,
+ init?: { status?: number; statusText?: string },
+): Response =>
+ new Response(body, {
+ status: init?.status ?? 200,
+ statusText: init?.statusText ?? 'OK',
+ });
+
+describe('RestApiClient', () => {
+ const originalProcess = (globalThis as Record<string, unknown>).process;
+ const originalCommunicationApi = (globalThis as Record<string, unknown>)
+ .frontComponentHostCommunicationApi;
+
+ beforeEach(() => {
+ (globalThis as Record<string, unknown>).process = {
+ env: {
+ TWENTY_API_URL: 'https://api.twenty.test',
+ TWENTY_APP_ACCESS_TOKEN: 'app-access-token',
+ },
+ };
+ });
+
+ afterEach(() => {
+ (globalThis as Record<string, unknown>).process = originalProcess;
+ (globalThis as Record<string, unknown>).frontComponentHostCommunicationApi =
+ originalCommunicationApi;
+ vi.restoreAllMocks();
+ });
+
+ it('should call the resolved url with a bearer token and parse the JSON response', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(buildResponse(JSON.stringify({ id: '42' })));
+
+ const client = new RestApiClient({ fetch: fetchMock });
+
+ const result = await client.get('/s/my-app/my-route');
+
+ expect(result).toEqual({ id: '42' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ const [url, requestInit] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://api.twenty.test/s/my-app/my-route');
+ expect((requestInit.headers as Headers).get('Authorization')).toBe(
+ 'Bearer app-access-token',
+ );
+ expect(requestInit.method).toBe('GET');
+ });
+
+ it('should serialize a JSON body and set the content type on post', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(buildResponse('{}'));
+
+ const client = new RestApiClient({ fetch: fetchMock });
+
+ await client.post('/s/my-app/my-route', { name: 'Twenty' });
+
+ const [, requestInit] = fetchMock.mock.calls[0];
+ expect(requestInit.method).toBe('POST');
+ expect((requestInit.headers as Headers).get('Content-Type')).toBe(
+ 'application/json',
+ );
+ expect(requestInit.body).toBe(JSON.stringify({ name: 'Twenty' }));
+ });
+
+ it('should append query parameters while skipping nullish values', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(buildResponse('{}'));
+
+ const client = new RestApiClient({ fetch: fetchMock });
+
+ await client.get('/s/my-app/my-route', {
+ query: { limit: 10, search: undefined, includeArchived: false },
+ });
+
+ const [url] = fetchMock.mock.calls[0];
+ expect(url).toBe(
+ 'https://api.twenty.test/s/my-app/my-route?limit=10&includeArchived=false',
+ );
+ });
+
+ it('should throw a RestApiClientError when the api url is missing', async () => {
+ (globalThis as Record<string, unknown>).process = { env: {} };
+ const fetchMock = vi.fn();
+
+ const client = new RestApiClient({ fetch: fetchMock });
+
+ await expect(client.get('/s/my-app/my-route')).rejects.toBeInstanceOf(
+ RestApiClientError,
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('should throw a RestApiClientError when the access token is missing', async () => {
+ (globalThis as Record<string, unknown>).process = {
+ env: { TWENTY_API_URL: 'https://api.twenty.test' },
+ };
+ const fetchMock = vi.fn();
+
+ const client = new RestApiClient({ fetch: fetchMock });
+
+ await expect(client.get('/s/my-app/my-route')).rejects.toBeInstanceOf(
+ RestApiClientError,
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('should surface non-2xx responses as a RestApiClientError carrying the parsed body', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ buildResponse(JSON.stringify({ message: 'Not found' }), {
+ status: 404,
+ statusText: 'Not Found',
+ }),
+ );
+
+ const client = new RestApiClient({ fetch: fetchMock });
+
+ await expect(client.get('/s/my-app/my-route')).rejects.toMatchObject({
+ status: 404,
+ body: { message: 'Not found' },
+ });
+ });
+
+ it('should refresh the access token once on a 401 and retry the request', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(buildResponse('', { status: 401 }))
+ .mockResolvedValueOnce(buildResponse(JSON.stringify({ ok: true })));
+
+ const requestAccessTokenRefresh = vi
+ .fn()
+ .mockResolvedValue('refreshed-token');
+
+ (globalThis as Record<string, unknown>).frontComponentHostCommunicationApi =
+ { requestAccessTokenRefresh };
+
+ const client = new RestApiClient({ fetch: fetchMock });
+
+ const result = await client.get('/s/my-app/my-route');
+
+ expect(result).toEqual({ ok: true });
+ expect(requestAccessTokenRefresh).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(
+ (fetchMock.mock.calls[1][1].headers as Headers).get('Authorization'),
+ ).toBe('Bearer refreshed-token');
+ });
+});
diff --git a/packages/twenty-client-sdk/src/rest/index.ts b/packages/twenty-client-sdk/src/rest/index.ts
new file mode 100644
index 00000000000..73ec97ee021
--- /dev/null
+++ b/packages/twenty-client-sdk/src/rest/index.ts
@@ -0,0 +1,338 @@
+import {
+ DEFAULT_API_KEY_NAME,
+ DEFAULT_API_URL_NAME,
+ DEFAULT_APP_ACCESS_TOKEN_NAME,
+} from 'twenty-shared/application';
+
+const isDefined = <T>(value: T): value is NonNullable<T> =>
+ value !== null && value !== undefined;
+
+export type RestApiClientOptions = {
+ baseUrl?: string;
+ token?: string;
+ fetch?: typeof globalThis.fetch;
+ defaultHeaders?: HeadersInit;
+};
+
+export type RestApiRequestOptions = {
+ headers?: HeadersInit;
+ query?: Record<string, string | number | boolean | null | undefined>;
+ signal?: AbortSignal;
+};
+
+type RestApiClientErrorDetails = {
+ status?: number;
+ statusText?: string;
+ url?: string;
+ body?: unknown;
+};
+
+export class RestApiClientError extends Error {
+ readonly status?: number;
+ readonly statusText?: string;
+ readonly url?: string;
+ readonly body?: unknown;
+
+ constructor(message: string, details?: RestApiClientErrorDetails) {
+ super(message);
+ this.name = 'RestApiClientError';
+ this.status = details?.status;
+ this.statusText = details?.statusText;
+ this.url = details?.url;
+ this.body = details?.body;
+ }
+}
+
+type ProcessEnvironment = Record<string, string | undefined>;
+
+const getProcessEnvironment = (): ProcessEnvironment => {
+ const processObject = (
+ globalThis as { process?: { env?: ProcessEnvironment } }
+ ).process;
+
+ return processObject?.env ?? {};
+};
+
+const buildRequestUrl = (
+ baseUrl: string,
+ path: string,
+ query: RestApiRequestOptions['query'],
+): string => {
+ const url = /^https?:\/\//i.test(path)
+ ? path
+ : `${baseUrl}${path.startsWith('/') ? '' : '/'}${path}`;
+
+ if (!isDefined(query)) {
+ return url;
+ }
+
+ const searchParams = new URLSearchParams();
+
+ for (const [key, value] of Object.entries(query)) {
+ if (isDefined(value)) {
+ searchParams.append(key, String(value));
+ }
+ }
+
+ const queryString = searchParams.toString();
+
+ if (queryString.length === 0) {
+ return url;
+ }
+
+ return url.includes('?') ? `${url}&${queryString}` : `${url}?${queryString}`;
+};
+
+export class RestApiClient {
+ private baseUrl: string | undefined;
+ private token: string | undefined;
+ private defaultHeaders: HeadersInit | undefined;
+ private fetchImplementation: typeof globalThis.fetch | null;
+ private authorizationToken: string | null;
+ private refreshAccessTokenPromise: Promise<string | null> | null = null;
+
+ constructor(options?: RestApiClientOptions) {
+ this.baseUrl = options?.baseUrl;
+ this.token = options?.token;
+ this.defaultHeaders = options?.defaultHeaders;
+ this.fetchImplementation = options?.fetch ?? globalThis.fetch ?? null;
+ this.authorizationToken = options?.token ?? null;
+ }
+
+ request<TResponse = unknown>(
+ method: string,
+ path: string,
+ options?: RestApiRequestOptions & { body?: unknown },
+ ) {
+ return this.execute<TResponse>(method, path, options?.body, options);
+ }
+
+ get<TResponse = unknown>(path: string, options?: RestApiRequestOptions) {
+ return this.execute<TResponse>('GET', path, undefined, options);
+ }
+
+ post<TResponse = unknown>(
+ path: string,
+ body?: unknown,
+ options?: RestApiRequestOptions,
+ ) {
+ return this.execute<TResponse>('POST', path, body, options);
+ }
+
+ put<TResponse = unknown>(
+ path: string,
+ body?: unknown,
+ options?: RestApiRequestOptions,
+ ) {
+ return this.execute<TResponse>('PUT', path, body, options);
+ }
+
+ patch<TResponse = unknown>(
+ path: string,
+ body?: unknown,
+ options?: RestApiRequestOptions,
+ ) {
+ return this.execute<TResponse>('PATCH', path, body, options);
+ }
+
+ delete<TResponse = unknown>(path: string, options?: RestApiRequestOptions) {
+ return this.execute<TResponse>('DELETE', path, undefined, options);
+ }
+
+ private resolveBaseUrl(): string {
+ const baseUrl =
+ this.baseUrl ?? getProcessEnvironment()[DEFAULT_API_URL_NAME];
+
+ if (!isDefined(baseUrl) || baseUrl.trim().length === 0) {
+ throw new RestApiClientError(
+ `Missing API url. Set the \`${DEFAULT_API_URL_NAME}\` environment variable or pass \`baseUrl\` to \`RestApiClient\`.`,
+ );
+ }
+
+ return baseUrl.replace(/\/+$/, '');
+ }
+
+ private resolveToken(): string {
+ if (!isDefined(this.authorizationToken)) {
+ const processEnvironment = getProcessEnvironment();
+
+ this.authorizationToken =
+ this.token ??
+ processEnvironment[DEFAULT_APP_ACCESS_TOKEN_NAME] ??
+ processEnvironment[DEFAULT_API_KEY_NAME] ??
+ null;
+ }
+
+ if (
+ !isDefined(this.authorizationToken) ||
+ this.authorizationToken.length === 0
+ ) {
+ throw new RestApiClientError(
+ `Missing application access token. Set the \`${DEFAULT_APP_ACCESS_TOKEN_NAME}\` environment variable or pass \`token\` to \`RestApiClient\`.`,
+ );
+ }
+
+ return this.authorizationToken;
+ }
+
+ private async requestRefreshedAccessToken(): Promise<string | null> {
+ const refreshAccessTokenFunction = (
+ globalThis as {
+ frontComponentHostCommunicationApi?: {
+ requestAccessTokenRefresh?: () => Promise<string>;
+ };
+ }
+ ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;
+
+ if (typeof refreshAccessTokenFunction !== 'function') {
+ return null;
+ }
+
+ if (!this.refreshAccessTokenPromise) {
+ this.refreshAccessTokenPromise = refreshAccessTokenFunction()
+ .then((refreshedAccessToken) => {
+ if (
+ typeof refreshedAccessToken !== 'string' ||
+ refreshedAccessToken.length === 0
+ ) {
+ return null;
+ }
+
+ this.authorizationToken = refreshedAccessToken;
+ getProcessEnvironment()[DEFAULT_APP_ACCESS_TOKEN_NAME] =
+ refreshedAccessToken;
+
+ return refreshedAccessToken;
+ })
+ .catch((refreshError: unknown) => {
+ console.error(
+ 'Twenty REST client: token refresh failed',
+ refreshError,
+ );
+
+ return null;
+ })
+ .finally(() => {
+ this.refreshAccessTokenPromise = null;
+ });
+ }
+
+ return this.refreshAccessTokenPromise;
+ }
+
+ private sendRequest(
+ url: string,
+ method: string,
+ body: unknown,
+ token: string,
+ requestOptions?: RestApiRequestOptions,
+ ): Promise<Response> {
+ if (!isDefined(this.fetchImplementation)) {
+ throw new RestApiClientError(
+ 'Global `fetch` function is not available, pass a fetch implementation to `RestApiClient`.',
+ );
+ }
+
+ const requestHeaders = new Headers(this.defaultHeaders);
+
+ if (isDefined(requestOptions?.headers)) {
+ new Headers(requestOptions.headers).forEach((value, key) =>
+ requestHeaders.set(key, value),
+ );
+ }
+
+ const isFormDataBody =
+ typeof FormData !== 'undefined' && body instanceof FormData;
+ const shouldSerializeBody =
+ isDefined(body) && !isFormDataBody && typeof body !== 'string';
+
+ if (isFormDataBody) {
+ requestHeaders.delete('Content-Type');
+ } else if (shouldSerializeBody) {
+ requestHeaders.set('Content-Type', 'application/json');
+ }
+
+ requestHeaders.set('Authorization', `Bearer ${token}`);
+
+ const serializedBody = !isDefined(body)
+ ? undefined
+ : isFormDataBody || typeof body === 'string'
+ ? (body as BodyInit)
+ : JSON.stringify(body);
+
+ return this.fetchImplementation.call(globalThis, url, {
+ method,
+ headers: requestHeaders,
+ body: serializedBody,
+ signal: requestOptions?.signal,
+ });
+ }
+
+ private async parseResponse<TResponse>(
+ response: Response,
+ url: string,
+ ): Promise<TResponse> {
+ const rawBody = await response.text();
+ let parsedBody: unknown = undefined;
+
+ if (rawBody.trim().length > 0) {
+ try {
+ parsedBody = JSON.parse(rawBody);
+ } catch {
+ parsedBody = rawBody;
+ }
+ }
+
+ if (!response.ok) {
+ throw new RestApiClientError(
+ `Request to ${url} failed with status ${response.status} ${response.statusText}`,
+ {
+ status: response.status,
+ statusText: response.statusText,
+ url,
+ body: parsedBody,
+ },
+ );
+ }
+
+ return parsedBody as TResponse;
+ }
+
+ private async execute<TResponse>(
+ method: string,
+ path: string,
+ body: unknown,
+ requestOptions?: RestApiRequestOptions,
+ ): Promise<TResponse> {
+ const url = buildRequestUrl(
+ this.resolveBaseUrl(),
+ path,
+ requestOptions?.query,
+ );
+ const token = this.resolveToken();
+
+ let response = await this.sendRequest(
+ url,
+ method,
+ body,
+ token,
+ requestOptions,
+ );
+
+ if (response.status === 401) {
+ const refreshedAccessToken = await this.requestRefreshedAccessToken();
+
+ if (isDefined(refreshedAccessToken)) {
+ response = await this.sendRequest(
+ url,
+ method,
+ body,
+ refreshedAccessToken,
+ requestOptions,
+ );
+ }
+ }
+
+ return this.parseResponse<TResponse>(response, url);
+ }
+}
diff --git a/packages/twenty-client-sdk/vite.config.ts b/packages/twenty-client-sdk/vite.config.ts
index e4be0bb6a6d..b2dcc4848b0 100644
--- a/packages/twenty-client-sdk/vite.config.ts
+++ b/packages/twenty-client-sdk/vite.config.ts
@@ -6,6 +6,7 @@ import packageJson from './package.json';
const entries = [
'src/core/index.ts',
'src/metadata/index.ts',
+ 'src/rest/index.ts',
'src/generate/index.ts',
];
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
index 36f876a3b75..54c94745699 100644
--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx
@@ -200,45 +200,22 @@ export default defineFrontComponent({
Front components run browser-side in a sandboxed Web Worker, while [logic functions](/developers/extend/apps/logic/logic-functions) run server-side. There is no direct in-process call between the two — instead, a front component reaches a logic function over HTTP.
-A logic function declared with `httpRouteTriggerSettings` is exposed under the `/s/` endpoint at `${TWENTY_API_URL}/s<path>`. Your front component calls that route with `fetch`, authenticating with the `TWENTY_APP_ACCESS_TOKEN` that Twenty injects into the worker.
-
-A small reusable helper keeps the call sites clean:
-
-```ts src/shared/call-app-route.ts
-export async function callAppRoute(
- path: string,
- body: Record<string, unknown>,
-): Promise<unknown> {
- const apiUrl = process.env.TWENTY_API_URL ?? '';
- const token = process.env.TWENTY_APP_ACCESS_TOKEN;
-
- const res = await fetch(`${apiUrl}/s${path}`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- ...(token ? { Authorization: `Bearer ${token}` } : {}),
- },
- body: JSON.stringify(body),
- });
-
- if (!res.ok) {
- throw new Error(`Logic function failed (${res.status})`);
- }
+A logic function declared with `httpRouteTriggerSettings` is exposed under the `/s/` endpoint at `${TWENTY_API_URL}/s<path>`. Your front component calls that route with the `RestApiClient` from `twenty-client-sdk/rest`, which authenticates with the `TWENTY_APP_ACCESS_TOKEN` that Twenty injects into the worker.
- return res.json();
-}
-```
+The `RestApiClient` is built for exactly this. It reads `TWENTY_API_URL` and `TWENTY_APP_ACCESS_TOKEN` from the worker environment, attaches the `Authorization: Bearer` header, serializes and parses JSON, and throws a `RestApiClientError` when the token or URL is missing or the response is non-2xx — so you don't reimplement that boilerplate in every component.
A headless front component can run the call on mount via the `Command` component, then unmount automatically:
```tsx src/front-components/sync-prs.tsx
import { defineFrontComponent } from 'twenty-sdk/define';
import { Command } from 'twenty-sdk/command';
-import { callAppRoute } from 'src/shared/call-app-route';
+import { RestApiClient } from 'twenty-client-sdk/rest';
const SyncPrs = () => {
const execute = async () => {
- await callAppRoute('/github/fetch-prs', {
+ const client = new RestApiClient();
+
+ await client.post('/s/github/fetch-prs', {
owner: 'twentyhq',
repo: 'twenty',
});
@@ -256,7 +233,7 @@ export default defineFrontComponent({
});
```
-The `path` passed to `callAppRoute` must match the logic function's `httpRouteTriggerSettings.path` (the `/s` prefix is added by the helper):
+The path passed to the client is the route's public path — the logic function's `httpRouteTriggerSettings.path` prefixed with `/s`. Keep `isAuthRequired: true`; the client supplies the app access token Twenty mints for your component:
```ts src/logic-functions/fetch-prs.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk/define';
@@ -284,6 +261,48 @@ export default defineLogicFunction({
`TWENTY_API_URL` and `TWENTY_APP_ACCESS_TOKEN` are injected automatically — see [Application variables](#application-variables). Because secret application variables are never exposed to front components, keep API keys and other sensitive logic in the logic function, not in the front component.
</Note>
+### RestApiClient reference
+
+Import `RestApiClient` from `twenty-client-sdk/rest`. It belongs to the same client family as `CoreApiClient` and `MetadataApiClient`, but targets your app's HTTP routes instead of the GraphQL API.
+
+| Method | Description |
+|--------|-------------|
+| `get(path, options?)` | Sends a `GET` request |
+| `post(path, body?, options?)` | Sends a `POST` request |
+| `put(path, body?, options?)` | Sends a `PUT` request |
+| `patch(path, body?, options?)` | Sends a `PATCH` request |
+| `delete(path, options?)` | Sends a `DELETE` request |
+| `request(method, path, options?)` | Generic request with any HTTP method |
+
+`options` accepts `headers`, `query` (a record of query-string params; nullish values are skipped), and an `AbortSignal` via `signal`. A non-`FormData` object `body` is JSON-serialized automatically. On a `401`, the client refreshes the access token once through the host and retries the request.
+
+The base URL and token are resolved from the environment by default. Pass overrides to the constructor when needed — for example in tests:
+
+```ts
+const client = new RestApiClient({
+ baseUrl: 'https://api.example.com',
+ token: 'my-token',
+});
+```
+
+Failed requests throw a `RestApiClientError` exposing `status`, `statusText`, `url`, and the parsed `body`:
+
+```tsx
+import { RestApiClient, RestApiClientError } from 'twenty-client-sdk/rest';
+
+const client = new RestApiClient();
+
+try {
+ const prs = await client.get('/s/github/fetch-prs', {
+ query: { state: 'open' },
+ });
+} catch (error) {
+ if (error instanceof RestApiClientError) {
+ console.error(error.status, error.body);
+ }
+}
+```
+
## Accessing runtime context
Inside your component, use SDK hooks to access the current user, record, and component instance: