Skip to Content
GuidesWriting an Operation Endpoint

Writing an Operation Endpoint

An operation endpoint is a function you host and Foir calls. It is where your own logic lives — the thing no platform can write for you — and it is the only piece of server-side code a Foir app needs.

This guide is the practical companion to You Don’t Need a Backend. If you want the argument for why it’s shaped this way, start there, and see App architecture for the rule it follows: your frontend reaches your logic only by running the operation, and the endpoint calls Foir only with the dispatch token it is handed.

What you’re building

A single HTTP handler that:

  1. refuses anything Foir didn’t send,
  2. reads the run it was sent,
  3. does the work, calling Foir as the operation where it needs to,
  4. answers with a result, or accepts the job and reports back later.

It can live anywhere that serves HTTP: a route in your existing app, a Cloudflare Worker, a Lambda, a container. Foir does not host it, and that’s deliberate — no runtime to migrate to, and no lock-in beyond an HTTP call.

The endpoint, in three calls

import { createFoirClient } from '@foir/sdk/data'; import { readDispatch, requireScopedToken } from '@foir/sdk/server'; import * as generated from './send-quote.generated'; export async function POST(request: Request) { const { dispatch } = await requireScopedToken(request, { expectedProjectId: process.env.FOIR_PROJECT_ID, }); const { input } = await readDispatch<{ quoteId: string; email: string }>(request); const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, dispatch, generated }); const quote = await foir.quote.findUnique({ id: input.quoteId }); // ... send it ... return Response.json({ quoteId: quote?._id, sentTo: input.email }); }

The guard refuses anything Foir didn’t send, and hands back the token it verified as dispatch. readDispatch reads the run from the body. The client built from dispatch calls Foir as the operation, with exactly the grants the operation declares, so the same typed calls you would make anywhere else (queries, writes, execute<Op>) are answered for this operation and refused beyond it.

There is no key anywhere in that function, and there shouldn’t be. The dispatch token is the credential: a Foir key is needed only if the function calls Foir outside a dispatch.

Types for the operation’s token

generated is the module foir types --operation wrote for this operation, and a client built from a dispatch token takes no other:

foir types --operation send-quote --out src/send-quote.generated.ts

Its types are the surface the operation’s token is served, which is what the operation declared in its grants, so a call the token would be refused is a compile error in the endpoint instead. An operation that reads quotes and writes nothing gets foir.quote.findUnique and no foir.quote.create. The module names its operation (foirCredential), a client built from a key refuses it, and a dispatch client refuses a module generated for a key, or for another operation than the dispatch names.

The surface is described to someone who could author the operation, one holding operations:write: your signed-in session, with no key at all. Regenerate when the operation’s grants change.

1. Refuse anything that isn’t Foir

This is the whole security boundary, and it goes first. requireScopedToken throws a ScopedTokenError carrying the status to answer with: 401 for a missing or invalid token, 403 for a valid token minted for another project. readDispatch throws an OperationPayloadError (400) for a body that isn’t a dispatch. Map both in one place:

import { OperationPayloadError, ScopedTokenError } from '@foir/sdk/server'; try { return await handle(request); } catch (err) { if (err instanceof ScopedTokenError || err instanceof OperationPayloadError) { return Response.json({ error: err.message }, { status: err.status }); } throw err; }

Two details worth taking seriously:

  • Pin expectedProjectId from your own config, never from the request. Without it, a token minted for a different project is still a valid token.
  • Verify on every route Foir calls, including ones that look internal. Nothing else is guarding them.

requireScopedToken verifies against production’s keys by default. Against another environment, pass that environment’s jwksUrl.

2. Read the run

The body is the run, not the input. Reading it as though it were the input finds nothing, which is why readDispatch exists: it parses the body into a typed OperationPayload and refuses anything that isn’t one.

Field
executionIdThe run. Quote it in your logs
operationKeyThe operation being run
trigger.typeapi, ui, lifecycle (a hook) or schedule
inputWhat the caller passed. Always an object
contexttenantId, projectId, actorId, timestamp, and userId when the run acts for a user
record, content, triggerContextPresent only when the caller that started the run attached them
callbackPresent only on an async dispatch. A blocking (sync) dispatch carries no callback: your response body is the result

For a hook, the event’s own keys are in input: RECORD_PUBLISHED’s record id is input.recordId. Read the record back through the client when you need its content.

Alongside the body, X-Foir-Context carries correlation metadata:

project=prj_123;org_id=org_leeds;app=send_quote;operation=send_quote;triggered_by=api;execution_id=exe_456

org_id names the organization the run belongs to, and is absent for a run at the project itself. If your app serves several organizations, this is how you tell whose work you’re doing. You don’t need it to scope your calls: the dispatch token already carries the organization, so the client built from it reads and writes there.

3. Use a secret without holding one

Your function should carry no credentials. Keep the key in Foir’s vault and read it when the call needs it, with the token the call carried. X-Foir-Token carries what the operation declares and nothing else, so an operation that reads a secret declares the read: appsecrets:read for one an app or a config owns, secrets:read for one the project owns. Either reads only its owner’s secrets, in the project the call was made for.

const resp = await fetch(`${process.env.FOIR_API_URL}/graphql`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Foir-Token': request.headers.get('X-Foir-Token')!, }, body: JSON.stringify({ query: `query($ref: String!, $purpose: String!) { getSecret(ref: $ref, purpose: $purpose) { plaintextBase64 } }`, variables: { ref: RESEND_KEY_REF, purpose: 'send_quote' }, }), });

Your repository, your environment and your deploy pipeline hold a reference, never the key. See Secrets.

Nothing is substituted into the request Foir sends your function: an operation’s requestTemplate and secretBindings shape the calls Foir makes itself, to a third-party API, for a resolver operation or a pass-through write. Those calls go to the third party instead of to a function, and carry no Foir token. The call to your function is always the payload above, with the platform’s headers.

Keep secrets you read out of logs and error reports: they are ordinary strings once you hold them, which is exactly what makes them easy to print by accident.

4. Answer

Synchronously — return a JSON body and Foir stores it as the run’s result:

return Response.json({ quoteId, sentTo: input.email });

An empty body is fine and reads as a run with no result. A body that isn’t JSON fails the run with a named error rather than being silently dropped.

Asynchronously — return 202 with no body, do the work, then call back:

// exactly 202; any other 2xx is a protocol violation and fails the dispatch return new Response(null, { status: 202 });

The callback block, present only on an async dispatch, carries the endpoint and a token scoped to that one execution. Call it when you finish, or when you fail. If you never call back, the run times out on the operation’s callback TTL and retries according to its policy.

Respond within the operation’s timeout_ms, and keep responses under 5 MB.

5. Decide who may trigger it

Nothing above says who is allowed to run this. That’s set on the API key, not in your code:

  • A signed-in user runs it when their role grants operations:execute, which runs every operation, or operations:execute:<operation-key>, which runs this one alone. That is how every user checks out while only the users whose role grants it rebook.
  • Anyone at all runs it when a publishable key names it under What anyone can do without signing in — for a public “request a quote” or “notify me when it’s back”. Those runs count against the publishable key’s rate limit, and the operation’s own quotas, preconditions and second-factor requirement still apply.
  • A schedule or a hook runs it for scheduled or internal work: Foir triggers it itself, and no key is involved.

You change any of that in the console without touching the function.

Guarding an operation beyond the key

Three controls live on the operation itself, and they apply however it was triggered:

preconditionRefuse the run unless something is true of the request or the caller — including whether there’s a signed-in user at all
second_factorRequire a proven step-up. A caller who never signed in has nothing to prove, so this refuses them outright. Neither foir.config.ts nor the console sets it yet; it is set through the platform API’s UpdateOperation
quotasCeilings on the operation, independent of which credential asked

A publicly runnable operation that costs money should carry a quota. The per-visitor rate limit is a floor, not a budget.

Local development

foir operations dev receives dispatches on your machine without exposing a port, so you can develop against real triggers. Each dispatch arrives with the token and the body the platform minted for it, replayed to your local server as they are, so the three calls above run unchanged: the same guard, the same readDispatch, the same client built from the token. See operations in the CLI reference.

Last updated on