Building Operations
This guide walks you through building, deploying, and registering a custom operation endpoint in full. By the end, you’ll have a working service that receives requests from Foir, verifies the dispatch token, runs your logic, and returns or callbacks a result.
If you want the short version first, Writing an Operation Endpoint is the same thing in one page. If you want the reason this is the shape of a Foir app at all — rather than one more service behind an API tier you also maintain — read You Don’t Need a Backend.
What You’ll Build
A standalone Node.js (or Cloudflare Workers) service that:
- Receives scoped-token authenticated dispatches from the platform on
X-Foir-Token - Verifies the token against the platform’s JWKS endpoint
- Runs your custom logic (AI, data sync, etc.)
- Returns an
OperationResultinline (sync mode) or queues the work and reports back via a callback client (async mode)
Step 1: Scaffold the project
Use the Foir CLI to generate a starter project. The create-config command scaffolds a monorepo with a Vite UI app and a Hono API server with webhook and health routes:
npx @foir/cli create-config my-summarizer --type workflowThe --type flag accepts custom-editor, workflow, or widget. For an operation, workflow is the best fit. Omit it to be prompted.
Project structure:
my-summarizer/
package.json
foir.config.ts
ui/
package.json
src/
main.tsx
App.tsx
index.css
.env.example
api/
package.json
src/
index.ts # Hono entrypoint (port 3002)
routes/
webhooks.ts # Inbound webhook handlers (if needed)
health.ts
.env.examplecd my-summarizer
npm install
cp ui/.env.example ui/.env.local
cp api/.env.example api/.env.local
npm run devThe UI starts on http://localhost:3001, the API on http://localhost:3002.
Step 2: Implement your sync operation
Create api/src/routes/operations.ts, mount it in api/src/index.ts, and give it the dispatch-token middleware described in Step 4. Add your handler, and hand it the body as readDispatch(c.req.raw) reads it:
import type { OperationPayload, OperationResult } from '@foir/sdk/server';
type SummarizeInput = { text?: string; maxLength?: number };
async function handleSummarize(
payload: OperationPayload<SummarizeInput>
): Promise<OperationResult> {
const { input } = payload;
const content = input.text;
if (typeof content !== 'string' || content === '') {
return {
success: false,
error: {
code: 'VALIDATION_ERROR',
message: 'This operation requires `text` in its input',
},
};
}
const maxLength = input.maxLength ?? 200;
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{
role: 'user',
content: `Summarize in under ${maxLength} characters:\n\n${content}`,
},
],
}),
});
const data = await response.json();
return {
success: true,
result: data.choices[0].message.content,
metadata: {
model: 'gpt-4',
tokens: data.usage.total_tokens,
},
};
}Step 3: (Optional) async mode for long-running work
If your operation can run longer than a minute (large exports, image generation, batch jobs), declare it as mode: 'async' and respond with 202 Accepted. Use createCallbackClient to report progress and the terminal result:
import { createCallbackClient, readDispatch } from '@foir/sdk/server';
app.post('/operations/full-export', async (c) => {
const payload = await readDispatch(c.req.raw);
// `callback` is present only on an async dispatch.
if (!payload.callback) {
return c.json({ error: 'expected async dispatch' }, 400);
}
// Queue the work in your own durable runtime
await queue.add('full-export', {
executionId: payload.executionId,
callback: payload.callback,
input: payload.input,
});
return c.json({ accepted: true }, 202);
});
// In your queue worker:
async function processFullExport(job) {
const { executionId, callback, input } = job.data;
const cb = createCallbackClient(callback, {
executionId,
});
const items = await fetchAllItems();
for (let i = 0; i < items.length; i++) {
if (i % 100 === 0) {
const result = await cb.progress({
pct: Math.floor((i / items.length) * 100),
message: `Exported ${i} of ${items.length}`,
});
if (result.cancelled) return;
}
await exportItem(items[i]);
}
await cb.complete({ exportedCount: items.length });
}The callback client signs each request with the run’s own key, payload.callback.signingKey (an HMAC of the body), and bears the scoped callback token from payload.callback.token. The platform verifies both before accepting the callback. An endpoint that holds the project’s signing secret may pass it as signingSecret instead.
Step 4: Set up scoped-token verification
Operation dispatches carry a signed JWT in X-Foir-Token. Every route the platform dispatches to must verify it before doing anything else. Your endpoint has to be publicly reachable for the platform to call it — so its security is this verification. A route that skips it is an open endpoint anyone on the internet can call directly, bypassing the operation’s scopes, quotas, and preconditions.
The SDK makes the safe path one line:
import { Hono } from 'hono';
import {
requireScopedToken,
ScopedTokenError,
type ScopedTokenIngress,
} from '@foir/sdk/server';
const app = new Hono<{ Variables: { dispatch: ScopedTokenIngress } }>();
app.use('/operations/*', async (c, next) => {
try {
c.set(
'dispatch',
await requireScopedToken(c.req.raw, {
expectedProjectId: process.env.FOIR_PROJECT_ID,
}),
);
await next();
} catch (err) {
if (err instanceof ScopedTokenError) {
return c.json({ error: err.message }, err.status);
}
throw err;
}
});requireScopedToken:
- Extracts the token from
X-Foir-Token(missing → 401) - Verifies the JWT signature against the cached JWKS (5-minute TTL), validating
iss,exp, andnbf - Rejects a valid token bound to a different project or tenant with 403 when you pass
expectedProjectId/expectedTenantId— always pin these from your deploy’s own config, so a token minted for another project can never drive your handler - Returns the parsed claims, the
tenantId/projectId/appNamesubject, and theX-Foir-Contextcorrelation metadata
JWKS keys are cached automatically per isolate; you don’t need to manage that. (The lower-level verifyScopedToken remains exported if you need custom handling.)
Calling Foir from the handler
The verified token is also the handler’s credential. requireScopedToken returns it as dispatch, ready for the data client, which then calls Foir as the operation, with exactly the grants the operation declares:
import { createFoirClient } from '@foir/sdk/data';
// foir types --operation summarize --out src/summarize.generated.ts
import * as generated from './summarize.generated';
app.post('/operations/summarize', async (c) => {
const { dispatch } = c.get('dispatch');
const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, dispatch, generated });
// ...
});It sends the token as X-Foir-Token and never an api key. The service holds no Foir key of its own: a Foir key is needed only if it calls Foir outside a dispatch.
Hardening checklist
- Verify on every platform-called route — including “internal-looking” ones. The dispatch token is the trust anchor: the platform reserves
X-Foir-TokenandX-Foir-Context, and a request template cannot set them. A templated call goes to a third-party host and carries neither, so a route of yours that verifies the token is never behind a template. - Pin
expectedProjectIdfrom your own environment config, not from anything in the request. - Never log interpolated secrets. Secret bindings arrive already hydrated into headers/body — keep them out of logs and error reports.
- Respond within the operation’s
timeout_msand keep responses under the platform’s 5 MB cap; oversized or slow responses fail the execution. - What the token carries: for record-touching handlers, honor the models its grants name (
recordsReadModels(claims),recordsWriteModels(claims),recordsCreateModels(claims)) rather than assuming full access.
What about FOIR_SIGNING_SECRET?
The legacy HMAC-based dispatch path is retired. You no longer need FOIR_SIGNING_SECRET for inbound verification.
You do not need it for async callbacks either: the callback client signs them with the run’s own callback.signingKey, which the platform sends with every async dispatch. foir push writes the project’s signing secret to your local .env as FOIR_SIGNING_SECRET (with a credential that holds opsecrets:read), and an endpoint may pass it to the callback client as signingSecret in place of the run’s key.
Step 5: Develop locally
Run the API on your machine and hold a dev session for the project:
foir operations dev --port 3002Each dispatch for the project arrives down the session and is POSTed to http://localhost:3002 at the path the operation is registered at, with the token and the body the platform minted for it. Nothing is exposed to the internet, and nothing in the handler changes: the token verifies, readDispatch reads the same body, and the client built from the token calls Foir as the operation, exactly as it will once deployed. Trigger the operation the way your users will, or from the console once it is registered (Step 7).
Step 6: Deploy
Deploy your service to any host (Vercel, Railway, Render, Cloudflare Workers, Fly.io, Docker, etc.).
For the API:
cd my-summarizer/api
npm run build
PORT=3002 npm startbuild compiles the server with tsc into dist, and start runs dist/index.js with Node. In development, npm run dev runs it from source with tsx and restarts it on each change.
For the UI (if you have one):
cd my-summarizer/ui
npm run build
# Serve dist/ from any static hostThe deployed URL is what you’ll register in the next step.
Step 7: Register in Foir
You can declare the operation in foir.config.ts and push, or create it manually in the console.
Via foir.config.ts (preferred)
import { defineConfig, defineOperation } from '@foir/cli/configs';
export default defineConfig({
key: 'my-summarizer',
name: 'My Summarizer',
operationBaseUrl: 'https://my-summarizer.vercel.app',
operations: [
defineOperation({
key: 'summarize',
name: 'AI Summarize',
endpoint: '/operations/summarize',
mode: 'sync',
timeoutMs: 30_000,
}),
defineOperation({
key: 'full-export',
name: 'Full Export',
endpoint: '/operations/full-export',
mode: 'async',
callbackTtlSeconds: 3600,
}),
],
});foir pushIn the console
- Go to Automation → Operations
- Click New Operation
- Fill in:
| Field | Example Value |
|---|---|
| Key | summarize |
| Name | AI Summarize |
| Endpoint URL | https://my-summarizer.vercel.app/operations/summarize |
| Supports async callback | Off |
| Timeout | 30000 |
- Save and activate the operation.
Operation configuration options
| Field | Description |
|---|---|
| Key | Unique identifier (kebab-case). |
| Name | Display name. |
| Description | What this operation does. |
| Category | Optional grouping label. |
| Kind | How the operation surfaces in the public API: a mutation, a query or a model field. |
| Endpoint URL | Your service’s URL. |
| Supports async callback | On for an operation that answers 202 and calls back when the work finishes. |
| Models | Models this operation is attached to. |
| Timeout (ms) | Max time to wait for the endpoint to respond. |
| Grants | What the dispatch token carries, in the permission catalogue’s names, e.g. records:read:product, users:create. Not on this form: set them in foir.config.ts and push. See Operation permissions. |
| Retry Policy | HTTP-dispatch retries (network/5xx). |
| Callback TTL | (async) How long the platform waits for a callback before timing out. |
| Callback Timeout Retry | (async) Retries when a callback times out, distinct from dispatch retries. |
| Input | The fields a person fills in before running the operation. |
| Input Schema / Output Schema | JSON Schema the input is validated against, and the shape of the result. |
| Allowed Permissions | Permission verbs a caller must all hold to trigger this operation. Leave empty for no gate. |
Step 8: Use the operation
In the console
For field operations: open any record with the targeted field type, click the operations menu on the field, select your operation.
For record operations: open any record of the targeted model, click the operations menu in the toolbar, select your operation.
Via the public API
The public API is per-operation typed: an operation keyed summarize is exposed as executeSummarize. The mutation returns an Execute<Op>Payload envelope: execution is always present, and result carries the typed output (populated on SYNC, null on ASYNC). Requires the operations:execute scope, or operations:execute:summarize for this operation alone.
mutation {
executeSummarize(input: { maxLength: 200 }, mode: SYNC) {
execution {
id
status
}
result {
summary
}
}
}The same dispatch through the data client:
const dispatched = (await foir.ns.operations['execute.summarize']({
input: { maxLength: 200 },
mode: 'SYNC',
})) as { execution: { id: string; status: string }; result: { summary: string } | null };Note: the data client addresses the operation by its key prefixed with
execute.—execute.summarize— while GraphQL addresses it by the generated fieldexecuteSummarize.operationsis the only namespace where those differ. It is on your client only if your key holdsoperations:execute.
There is no separate content argument: pass everything through the typed input. With a publishable or a server key, run reads, cancellation and subscriptions require a signed-in user and reach only that user’s runs. For async operations, read terminal state with operationExecution(id: $executionId) (scope operations:read) or subscribe to the per-operation operation<Op>Execution subscription; see Real-time and Subscriptions.
The Payload and Result Contract
OperationPayload (what your endpoint receives)
Read it with readDispatch(request), which parses the body into this type and refuses a body that isn’t one.
| Field | Description |
|---|---|
executionId | The execution row id (echo back on callbacks). Always present. |
operationKey | The operation’s unique key. |
trigger | How the operation was invoked: type is api, ui, lifecycle or schedule. |
input | The caller’s input. Always an object. |
context | tenantId, projectId, actorId (empty when nobody started the run), timestamp, and userId when the run acts for a user. |
content | Present only when the caller that started the run attached a content block. |
record | Present only when the caller that started the run attached a record block, forwarded as written. |
triggerContext | Present only when the caller supplied one. |
callback | Async only: the callback token, GraphQL endpoint and per-op mutation names. A blocking (sync) dispatch carries no callback; the response body is the result. |
OperationResult (sync only)
On success:
| Field | Description |
|---|---|
success: true | Indicates success. |
result | Result value (new field value for transforms, status data for record ops). |
metadata | Optional diagnostic info. |
On error:
| Field | Description |
|---|---|
success: false | Indicates failure. |
error.code | A short machine-readable code you choose (e.g. VALIDATION_ERROR, MISSING_INPUT, PROCESSING_FAILED). |
error.message | Human-readable error description. |
For async dispatches, you don’t return a result body — you return 202 Accepted and call cb.complete(result) / cb.fail(code, message) from your queue worker.
Tips
- Start with
foir create-config: it gives you a working project with Hono routing wired up. Add the token verification from Step 4 to every route the platform calls. - Always verify
X-Foir-Tokenin production. Without verification, anyone could send fake requests to your endpoint. - Pick the right mode. Sync for sub-minute deterministic work; async for anything that can run long, anything you want progress on, or anything that depends on a slow upstream.
- Call Foir as the operation instead of holding a long-lived Foir key in your service: build the data client from the
dispatchthatrequireScopedTokenreturns. The grants the operation declared are the grants the dispatch token carries. - Return meaningful error codes. The platform displays the
error.messageto users and uses theerror.codefor retry decisions. - Keep operations focused. One operation should do one thing well. Create multiple operations rather than one that branches on input.
- Set appropriate timeouts. AI operations might need 30–60 seconds. Simple data sync might need 5 seconds. Match the timeout to your use case.
Next Steps
- Operations Concepts — How operations fit into the platform
- Operation Configuration — Full
defineOperationreference - Editor SDK Server API —
verifyScopedToken,createCallbackClient, and friends - Building an App — When you want to ship a reusable installable unit, not just a private operation