Skip to Content
API ReferenceAuthentication

Authentication

Every request to the Foir data API carries a credential, and there are three classes of them. The class says who is calling: your app (a publishable key, or a server key on the server that renders its pages, plus the person’s own bearer when someone is signed in), an operation (its dispatch token), or a machine of your own (an admin key). Which to use where is on Credentials, and how an app is put together around them is on App architecture. This page is what each may hold and how it is sent.

The three credential classes

CredentialSent asHeld byWhat it may hold
Publishable key (foir_pub_)x-api-keyYour app: a browser, a mobile app, anythingWhat a stranger may do, and, with a signed-in user’s bearer, what that user’s role grants. Nothing kept for an admin key. Safe to ship in a bundle
Server key (foir_srv_)x-api-keyThe server that renders your app’s pagesWhat a publishable key may, and it may say who and where the visitor it calls for is. Never a browser
Admin key (foir_adm_)x-api-keyA machine of your own: integration sync, CI seeds, config push, back-office toolingThe permissions you give it, the management ones included. Nobody signs in through it, and it expires. Never your app, and never a browser
Dispatch tokenX-Foir-TokenAn operation’s endpoint, for the run it was handedThe grants the operation declared, and the user who triggered the run. Minted by Foir for each dispatch

A key is its kind’s prefix (foir_pub_, foir_srv_ or foir_adm_) followed by 49 letters and digits, the last six of which are a checksum. There is no separate live/test environment. Every key this API serves is bound to exactly one project, and nothing a request carries can move it to another.

No credential acts as a user it is not. A user is reached either by that user, with their own bearer, or by an operation they ran; a key never names a user to act as, and Foir refuses a request that tries (why).

Publishable keys

A publishable key is your app’s credential. To a visitor who is not signed in it gives what you named under What anyone can do without signing in and nothing else: for most apps the key’s reads, which return only published content (a preview environment’s own key also returns drafts, see Preview Mode Access). A signed-in user’s bearer adds what their role grants. See what a publishable key can actually do at request time.

PrefixBehavior
foir_pub_A visitor does only what the key gives; reads return published content only, unless it is a preview environment’s own key holding drafts:read. May hold writes, which act for a signed-in user whose role grants them. Cannot be made holding anything kept for an admin key (refused when the key is made, with the reason). Safe to embed in browser bundles.

The user’s bearer travels beside it in Authorization: Bearer, and a request carrying both is the user acting as themselves: see User token Authentication.

Server keys

A server key is your app’s credential on the server that renders its pages: a Next.js or Remix server, a Hydrogen storefront, a worker at the edge. It gives a visitor exactly what a publishable key gives, and a signed-in user’s bearer travels beside it the same way.

PrefixBehavior
foir_srv_Gives a visitor what a publishable key may give. Holds what a publishable key may hold, and two things more: visitors:forward, to say who and where the visitor it calls for is, and records:read.all, as the ceiling for a signed-in person whose role carries it. The API rejects it on requests that carry a browser Origin / Sec-Fetch-Site.

A server key never expires, so a lapsed key cannot take your pages down. Keep it out of client-side code, browser bundles and public repositories.

Admin keys

An admin key is for a machine of your own writing to Foir: an integration syncing another system, a CI job seeding content, a config push, your own back-office tooling. It is never your app’s credential, in the browser or on a server that renders your pages. That server holds a server key, and anything your app does beyond what a user may do themselves is an operation.

PrefixBehavior
foir_adm_Holds the permissions it is made with, including the ones only an admin key may hold, such as records:write.all and models:write. Gives nobody anything: a sign-in, a token refresh, or a user’s bearer sent beside it is refused. It expires, and can be renewed with the same secret (An admin key expires). The API rejects it on requests that carry a browser Origin / Sec-Fetch-Site.

Admin keys should never be exposed in client-side code, browser bundles, or public repositories. See a key that leaks.

Dispatch tokens

When a user (or a hook, or a schedule) runs an operation, Foir dispatches it to the operation’s endpoint with a signed, short-lived token in X-Foir-Token. The endpoint verifies it and builds its data client from it, with no key:

const { dispatch } = await requireScopedToken(request, { expectedProjectId }); const foir = createFoirClient({ apiUrl, dispatch, generated });
  • It holds the grants the operation declared, and nothing else. records:attribute, the grant to name the user a record belongs to, is one an operation declares for the models it writes users’ rows on. See Operation permissions.
  • It carries the user who triggered the run, when one did. That user decides the record’s ownership, the rows the run is confined to, the audit actor and the quotas charged.
  • A guarded field asks the grants it declared, for reads and writes alike, even when it carries a user; a user’s own request asks what their roles give them. See Guarded fields.

See Writing an Operation Endpoint for the endpoint, and Writing for a user from an operation for writing records a user owns.

One key, one project

Every API key this API serves is created inside a project and serves that project alone. A deploy that reads two projects holds two keys.

That is a containment property, not a limitation to work around: the project a request acts on is fixed by the credential, so no header, body field or forged input can steer a key at a project it was not issued for.

The one key with no project is an admin key made for a workspace itself. It acts on the workspace, and this API refuses it.

Authentication Methods

Include the API key in the x-api-key header:

curl -X POST https://api.foir.dev/graphql \ -H "Content-Type: application/json" \ -H "x-api-key: foir_pub_..." \ -d '{"query": "{ page(naturalKey: \"homepage\") { _id } }"}'

A request may instead carry a signed-in person’s token alone, in Authorization: Bearer, with no key. It then acts with what the token carries, where the token names, and with nothing a key gives a visitor. With a key, the key is read first and a token beside it is the person signed in to that key’s app: see User Token Authentication.

Selecting an Organization (X-Org-Id)

A project’s key, of any kind, names the organization it acts in for one request with the X-Org-Id header:

curl -X POST https://api.foir.dev/graphql \ -H "Content-Type: application/json" \ -H "x-api-key: foir_adm_..." \ -H "X-Org-Id: <organization-id>" \ -d '{"query": "{ orders(first: 10) { edges { node { _id } } } }"}'

The request is then bound to that organization exactly as one on a credential confined to it: reads see the organization’s rows, the rows of every organization nested under it, and the project-shared tier, writes are stamped into it, and an organization-owned record created without an explicit owner belongs to it.

  • Not an active organization of the key’s own project → 404 — organization not found. Unknown, suspended, pending deletion and another project’s organization all get this one answer, so the header cannot be used to find out which organizations exist.
  • A key already confined to an organization names a different one → 403 — X-Org-Id names an organization other than the one this credential is confined to. The header can narrow a project key; it cannot widen or redirect a confined one. That includes an organization nested under the key’s own: a confined key already reads those, and it names only its own organization.
  • A request acting for a user who does not stand in the named organization → 403 PERMISSION_DENIED.

Without the header a project key stands in no organization and reads the project-shared tier only — see what a credential with no organization reads. The header enters the response-cache key, so two organizations’ answers never share an entry, and it is on the CORS allow-list. The SDK sends it from the client-level orgId option, or from a per-call one for the odd request that acts elsewhere (acting inside an organization). It names a subtree: organizations nest and reach runs downward, so a reseller’s id covers every client beneath it — send the narrowest id that covers the request.

By the page address (X-Org-Url)

An app that knows only the page it is serving names the organization by that page’s URL instead, with any key of the project, a publishable one in the browser included:

curl -X POST https://api.foir.dev/graphql \ -H "Content-Type: application/json" \ -H "x-api-key: foir_pub_..." \ -H "X-Org-Url: https://saasapp.com/daves/menu" \ -d '{"query": "{ menuItems(first: 10) { edges { node { _id } } } }"}'

The URL resolves to the organization whose registered address (its app base URL, or a verified custom domain bound to it) is the URL’s longest prefix at a path-segment boundary, and the request is then exactly one that sent that organization’s X-Org-Id. A URL no active organization’s address covers answers the same 404 — organization not found. A key confined to an organization may use only that organization’s own addresses. Sent with X-Org-Id, the two must name the same organization. The rules and a table of worked addresses are in finding the organization from the page address. The SDK sends it from the orgUrl option.

API Key Scopes

Each key holds a list of permissions, in the permission catalogue’s names, and a publishable or a server key keeps a second list of what it gives a caller with nobody signed in. Both are chosen when the key is made or edited: in the console, with foir api-keys, or in foir.config.ts.

Every permission a key of each kind may hold, and what a publishable or a server key may give, is on the generated Key Permissions page, each with the permission catalogue’s own sentence. It is emitted from the list the platform checks a key against, so it cannot fall behind, and this page keeps no table of its own.

What a table cannot say is in the sections below:

Changing a record takes reading it

A read and a write are separate permissions, and holding the write of a model does not let a caller read it. Only making a record stands alone. Every write that finds a record already there needs records:read for the same model beside its own permission:

To do thisA caller holds
Create a recordrecords:create (per model on what a publishable or a server key gives a visitor: records:create:<model>)
Update or rename a recordrecords:write and records:read
Delete a recordrecords:delete and records:read
Publish or unpublish a recordrecords:publish and records:read

The same holds per model: records:write:order needs records:read:order. A caller without the read is refused, and the refusal names it: missing required scope: records:read:order: it goes with records:write:order, because changing a record already there takes reading it.

A caller that may create records of a model and may not read them is answered with the new record’s _id and nothing else. Asking for any other field of the new record is refused before anything is written, so a create is never made and then answered with an error. The data client asks for the whole record by default, so pass pick: ['_id']:

const { record } = await foir.enquiry.create({ input: { email, message }, pick: ['_id'], });

Who this reaches:

  • An admin key that held records:write, records:delete or records:publish before this rule keeps reading what it changes: it holds records:read beside each.
  • A publishable key, a server key, a user’s role and an operation hold what they list. Give each the read of every model it updates, deletes or publishes.
  • A signed-out visitor makes records through create<Model>, like everybody else, where the key gives the model’s create. See what nobody chooses.

The key editor and both role editors tick the read when you tick the write, and say why. Untick it to leave a credential that can only create.

What a publishable key may hold

A publishable key can hold writes, and the read-only-ness people associate with one is a property of the caller, not of the key.

What a publishable key may be made holding is a fixed list: a publishable key, what it may hold. It is the permissions of what the browser data plane serves (records, files, search, schemas, operations, notifications, notes, schedules, drafts, users, members and the sign-in), with no wildcard and nothing at every owner’s reach. A server key may hold the same list and two things more: visitors:forward and records:read.all.

Anything else is refused when the key is made, and the refusal says why. A publishable key sits in a page, so it is refused every owner’s rows (records:read.all, files:read.all), the project’s secrets and events, the organization registry, the keys themselves (apikeys:read, apikeys:write), operations:write, and records:attribute, which names the user a record belongs to. A wildcard is refused too (records:*, *): it grows with every permission added later.

What a publishable key can actually do at request time

Holding a permission is not giving it. What a caller with nobody signed in gets is what the key gives: the list its row keeps for that (a key’s two lists), and nothing worked out from what the key itself holds. An empty list gives a visitor nothing. A server key is the same in all of this: it gives a visitor what its own list says. A visitor refused something the key holds is told so: the refusal names the permission and adds that the key holds it and gives it to nobody who is not signed in.

That list may name a read, the sign-in a visitor needs before they are anyone, and a write in three forms only: records:create:<model> and operations:execute:<op>, each written down one model or operation at a time, and notes:create. They are what make an unauthenticated contact form, and a feedback box, possible without relaying either through a server holding an admin key.

One thing adds to it, and nothing else can: a signed-in user. With a user token, the caller gets their role’s scopes beside what the key gives. This is the ordinary path for “let a logged-in user edit their own record”.

No mutation is anonymous by design any more. A visitor writes a note through writeNote, the same field a signed-in user writes one through, and is asked the same permission, notes:create. Before, a visitor’s note was taken because the key itself held notes:write, which was nothing the visitor held.

What a request with nobody signed in may choose

A request that came through a publishable or a server key with nobody signed in acts for nobody: a publishable key sits in a page where anyone may present it, and a server key presented alone speaks for a visitor. Where the key gives it a create, it chooses the row’s content and the platform chooses the rest:

  • Where the row lands. At the level the key is confined to, never the one the request names. X-Org-Id narrows what a visitor reads. On a write it would choose where the row goes, so a project-wide key lifted from a page would file into any organization of the project.
  • The row’s key. create<Model> refuses a naturalKey from a visitor, and says to leave it out.
  • What comes back. A visitor who cannot read the model is answered with the new record’s _id alone. A visitor’s note is answered with its id and createdAt.

The same field serves a signed-in user, an admin key and an operation, each of which the platform can name: they write where their request stands, name a key for the row, and read back what they may read.

A retry is remembered for a visitor as for anybody else: send the same idempotencyKey with the same request and the first answer comes back. Every visitor presents the same publishable key, so the key has to be one no other visitor would send: the data client makes a random one for each create. The same key with a different request is refused.

createMyNote is the older name of writeNote for a signed-in user. It is the same create and still answers, marked as replaced in the schema, until the callers that name it have moved.

There is no key-type write gate anywhere in this: the write comes from the union above, not from the key’s prefix.

So a publishable key that holds records:write gives that write to no visitor, and a user becomes able to write through it the moment they sign in and their role says so. That is a stronger statement than “publishable keys are read-only”, and it is the one the platform actually implements.

Cross-user reads inside an organization

records:read.all is what lifts the per-user narrowing, and it is charged the same way whichever side of the request it arrives on.

A member of an organization reads only the rows they own unless their organization role carries it. Holding a role is not itself the capability: a door helper granted records:read sees their own rows, and a manager whose role adds records:read.all sees the organization’s. That is what makes “may read orders but not the takings” a role your app declares rather than a screen it hides.

A role can carry it for every model, or for the models it names: records:read.all:order reads every user’s orders in the organization and nobody else’s profiles. Tick it beside a model in the role editor, or grant it by name from the CLI.

The same applies to every request acting for a user: the user’s own role decides what they may enumerate, up to what the key they came through holds. A server key may hold records:read.all for that: it is then the ceiling for a signed-in person whose role carries it, such as your own staff, and it gives it to no visitor. A publishable key may not hold it. An admin key that itself holds records:read.all reads every owner’s rows: that is the back-office credential the permission exists for.

Writing for a user who is not the one signed in (a guest’s order, a sale rung up at the till, a ticket handed to a friend) is done from an operation, which names the user as the record’s owner under the grant it declared. See Writing for a user from an operation.

Membership still bounds the outside of this. A member reaches nothing outside their organization and the organizations nested under it, whatever their role says, and a member with no role reaches nothing at all.

Per-operation scopes

operations:execute grants every operation in the project. To limit a key, a role or a stranger to specific operations, grant the three-part form instead, one entry per operation:

operations:execute:checkout operations:execute:enrich_url

The restriction is enforced at two levels:

  • Schema: execute<Op> mutations for unlisted operations are absent from the schema that key sees — introspection and codegen included. Calling one fails GraphQL validation (Cannot query field ...) rather than reaching execution.
  • Execution: the public API refuses an unlisted operation with missing required scope: operations:execute:<operation-key>, and the platform refuses it again on its own (the caller lacks required permission operations:execute:<operation-key>).

A key holding the unscoped operations:execute satisfies every per-operation requirement, so existing keys behave exactly as before. The per-operation form covers every kind of operation: execute<Op>, a query operation’s root field and a field operation’s model field all charge it. cancelOperationExecution requires the unscoped form.

A role grants operations the same way. The storefront’s key holds operations:execute, so every operation is in its schema, and each user’s role decides which of them that user may run. A role granting operations:execute:checkout lets its users check out and refuses them rebook_order, naming the scope; a role granting the bare operations:execute runs every operation, as it always has. What a stranger with no account may run is the key’s anonymous list alone, one operation at a time.

userRoles: [ { key: 'shopper', name: 'Shopper', isDefault: true, grants: ['records:read:order', 'operations:execute:checkout'] }, { key: 'staff', name: 'Staff', grants: ['records:read:order', 'operations:execute'] }, ],

A role naming an operation the project does not have is refused at push, and in the console’s role editor, by name.

In the dashboard this is authored with the Operation Access selector on the key form; via the CLI, name each operation directly: foir api-keys create --grants operations:execute:<operation>.

Model-restricted keys

A key reaches every model only when its maker chooses All models (all_models on the platform API, allModels: true in foir.config.ts). Otherwise it carries a model allow-list (the Model Access selector on the key form), and its record scopes are bounded to the listed models. A key whose list is empty reads no model’s records:

  • Typed fields for unlisted models (tag, createTag, searchTags, …) are absent from the key’s schema and denied if called.
  • The generic record fields — record, records, recordVersions, searchRecords, batchRecordOperations — are unavailable to a model-restricted key, since they can reach any model. Use the typed per-model fields.
  • Responses are cached separately per restriction, so a restricted key can never be served another key’s cached data.

Semantic search on a model-restricted key

The allow-list removes the semantic-search scopes from the key rather than bounding them to the listed models. The embeddings plane has no per-model form: its searches run across models and its writes name a record, not a model, so there is nothing to narrow it to.

Scope the key holdsWhat the allow-list does to it
search:readNarrowed to the listed models. search<Type>s keeps working for each listed model with embeddings enabled, and searchRecords is unavailable
embeddings:readRemoved
embeddings:writeRemoved
search:*Narrowed to search:read for the listed models

So a model-restricted key cannot use the embeddings plane, whichever of these it was granted:

  • searchEmbeddings, findSimilarRecords, embeddingsForRecord, embeddingCoverage, embeddingDigests, writeEmbeddings, generateEmbedding and deleteEmbeddings are absent from the key’s schema and denied if called, and a list asked for missingEmbedding is refused.
  • The _hasEmbedding and _embeddingContentHash record fields resolve to null.
  • An agent connecting to the MCP server with the key is not offered foir_semantic_search, foir_embedding_coverage or foir_manage_embeddings.

Semantic search itself stays available in its per-model form, through search<Type>s. A caller that needs the embeddings plane directly needs a key without a model allow-list.

The allow-list does not apply to the global * scope. A key holding * keeps it unchanged, so that key reaches every model, on the embeddings plane and everywhere else, whatever models it lists.

Keys that manage keys

An admin key holding apikeys:read or apikeys:write (or apikeys:*, which is the two together) manages the API keys of its own project. It never reaches another project’s keys or the workspace’s own, and neither a publishable nor a server key can hold either permission.

Every operation is capped at the calling key’s own authority, so a key can never use these scopes to obtain a key broader than itself:

  • Create. The new key’s scopes must be ones the calling key holds. If the calling key has a model allow-list or a file-type allow-list, the new key needs one that stays within it; a new key with no list would be wider, so it is refused.
  • Rotate, update, revoke, and retiring a previous secret. Refused on a key holding a scope the calling key does not, or confined less narrowly than it. An update must also leave the key within the calling key’s authority.
  • List. Returns only the keys the calling key could act on. The total counts the same keys.

A refusal is PERMISSION_DENIED and names what is wider, for example api-key cannot rotate a key holding a scope beyond its own authority: records:write or api-key cannot issue a key confined less narrowly than itself: allowed_file_types must name a subset of the caller's own allowed_file_types.

A key confined to an organization manages no keys at all, not even its own organization’s. Credential management sits above the organization, so neither scope can grant such a key anything, and creating or updating a confined key to hold one is refused with scope "apikeys:write" grants nothing on an organization-confined key, so such a key may not hold it. Every key-management operation also refuses a confined credential outright, listing included.

A key holding * has the same key management and nothing more: it manages the keys its own authority covers, in its own project.

User Token Authentication

For features your users sign in for (their own areas, user-owned records, personalized content), your app sends its publishable key with the signed-in user’s own JWT, or its server key from the server that renders its pages. That pair is the user acting as themselves: every request is gated by their role.

After a user logs in via the User Auth mutations, they receive an access token. Include both the API key and the user token in subsequent requests:

curl -X POST https://api.foir.dev/graphql \ -H "Content-Type: application/json" \ -H "x-api-key: foir_pub_..." \ -H "Authorization: Bearer eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9..." \ -d '{"query": "{ currentUser { id email } }"}'
const response = await fetch("https://api.foir.dev/graphql", { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": process.env.NEXT_PUBLIC_FOIR_API_KEY, "Authorization": `Bearer ${userAccessToken}`, }, body: JSON.stringify({ query, variables }), });

The API key identifies the project and the JWT identifies the user. A user’s token sent beside an admin key is refused: nobody signs in through one. Requests with a valid user token can access user-specific queries like currentUser and records scoped to that user.

User access tokens are short-lived EdDSA JWTs whose iss is the issuer the discovery document names: https://api.foir.dev, or the project’s login domain for someone who signed in through it. You don’t need to verify them yourself, because the platform does, but if a server of yours wants to (one holding a user’s own session, say), fetch the public keys from https://api.foir.dev/.well-known/jwks.json. Never ship a token verifier to the browser.

When a user token is rejected

A user token is optional. If it fails to verify, the request is not refused — it is served as an ordinary anonymous read, because plenty of reads legitimately have no user signed in and rejecting them would break every signed-out page view.

That is the right behaviour, and it has a sharp edge: a lapsed token and a genuinely anonymous request produce the same 200 response. Nothing throws, no refresh path arms, and auth-targeted content quietly resolves to its anonymous variant. The failure surfaces as wrong content, never as an error.

So when Foir discards a token you sent, it says so:

{ "data": { "menu": { "...": "..." } }, "extensions": { "auth": { "userToken": "rejected", "reason": "expired", "servedAs": "anonymous" } } }
reasonWhat happenedWhat to do
expiredThe token verified as ours and its lifetime had passed.Re-exchange for a fresh token and retry.
invalidAnything else the verifier refuses — bad signature, unknown issuer, malformed.Check you are sending a user token, from this environment.
wrong_projectThe token is valid but belongs to a different project than your API key.Your two credentials disagree; check which project each is for.

It appears only when a token was actually sent and rejected. A request with no Authorization header, or one whose token verified, carries no auth block at all — so its presence is always a signal, never noise. It is a report, not an error: the response is still 200, and the data is the anonymous read you were served.

The same reason is on the response header, which is what a proxy or an access log can see without parsing a body, and what the REST lane uses:

X-Foir-Auth-Downgraded: expired

It is exposed via CORS, so browser code can read it too:

const res = await fetch(url, { headers }); const downgraded = res.headers.get("X-Foir-Auth-Downgraded"); if (downgraded === "expired") await refreshUserToken();

On the subscriptions lane the socket authenticates once, at connection_init, so the same block rides the connection_ack payload rather than a per-response extension.

Why this is not a 401. Turning it into one would refuse every anonymous page view on a site that forwards a token when it has one. The behaviour has to stay permissive; only the reporting was missing.

Personalized & targeted reads

The user token isn’t only for user-owned queries like currentUser — forward it on content reads too to unlock auth/segment targeting and user-scoped records. Resolution keys off the request’s principal:

Credentials sentPrincipalcontext.authStatus
x-api-key onlya visitor, with what the key gives"anonymous"
x-api-key + user tokenthat user (their role)"authenticated"

So a variant rule such as authStatus equals authenticated only matches when the token is forwarded on that query. Send only the api-key and the read resolves as anonymous, and the variant never fires, even for a signed-in user. A rule naming authStatus equals anonymous matches a read sent with no user token.

Caching. An api-key-only read is identical for every anonymous visitor and is shared-cacheable; a token-bearing read resolves per-user and is not. Because the token only exists once a user signs in, anonymous traffic stays fully cacheable — only signed-in reads become per-user. So forward the token wherever content is personalized, which for most apps is everywhere the user is signed in.

To avoid wiring this per-query (and forgetting), @foir/sdk provides a session-bound content client that forwards the token automatically when present:

import { createFoirContentClient } from "@foir/sdk/client"; const foir = createFoirContentClient({ env, getToken: () => getUserToken(session), // your bearer, or null when signed out }); // Forwards the token when signed in → auth/segment targeting resolves as the // user. No token → what the key gives a visitor (shared-cacheable). Same call either way. const menu = await foir.request(GetMenuDocument, { naturalKey: "header" });

Preview Mode Access

Pass preview: true on any read query to receive the latest (working) version of a record instead of the published one, or send X-Foir-Schema-Channel: draft to serve the whole request from the draft channel, which reads drafted content as well as the draft schema. Both are gated behind the drafts:read scope.

drafts:read belongs on a preview environment’s own key: a publishable key, or a server key where a server renders the preview. The preview environment is the deployment your team reviews unpublished content on, and it has a key of its own, separate from the one your production app ships. Holding the scope is the decision to show drafts wherever that key goes, so anyone who can load the preview environment reads your drafts: keep it where your team works, not where users browse. The production key does not hold drafts:read, and keeps returning published content whatever a request asks for.

query PreviewPage { page(naturalKey: "home", preview: true) { _id _hasDraft blocks { __typename } } }

The same read through the data client — preview is an ordinary argument there too:

const page = await foir.page.findUnique({ naturalKey: 'home', preview: true });

_hasDraft comes back on the record without being asked for. The data client returns every scalar the credential can see, and the field only exists for a key holding drafts:read, so the preview key gets it and the production key has nothing to read. See Preview, Drafts & Edge.

To set this up:

  1. Create a publishable key for the preview environment in the dashboard (or a server key, where a server renders it), holding and giving records:read and drafts:read. It is a key of its own: the key your production app ships stays without drafts:read.
  2. Give it to the preview deployment the way the production deployment is given its key, for example as PLATFORM_PREVIEW_API_KEY beside FOIR_PREVIEW=true (From the environment).
  3. Pass preview: true, or send X-Foir-Schema-Channel: draft, from that deployment.

If a request passes preview: true without drafts:read, the API responds with an authorization error rather than silently returning published content, so a misconfigured preview deploy fails loudly instead of quietly serving stale data. The draft channel header is answered differently: a publishable or a server key without drafts:read that sends it is served the published copy, because such a key serves an app’s pages, where a refusal would take a site down over a header nobody there chose, and an admin key without it is refused with a 403.

Detecting drafts without loading them

Records resolved with a key that holds drafts:read carry a _hasDraft system field that reports whether unpublished changes exist. The field is omitted entirely for a key without drafts:read, so its mere presence in a response is itself information that callers without drafts:read cannot observe.

Cache safety

Responses that honour preview: true or the draft channel come back with Cache-Control: no-store, preventing CDNs and shared proxies from caching draft content even if a misconfigured upstream tries to. Neither is stored in Foir’s response cache or answered on the shared CDN read lane, so a published body is never served to a draft request, nor a draft to a published one.

Security Best Practices

Use Environment Variables

Never hardcode API keys in source code. Store them in environment variables:

// Node.js / Next.js const apiKey = process.env.FOIR_API_KEY; // Vite const apiKey = import.meta.env.VITE_FOIR_API_KEY;

Keep Admin Keys Out of Your App

An admin key belongs to a machine of your own: an integration sync, a CI job, a config push, your back-office tooling. It is not your app’s credential, and that includes the server that renders your pages: a server component or loader reads with your server key, and with the user’s bearer when someone is signed in. Anything your app does beyond that is an operation. Never include a server key or an admin key in a client-side bundle.

// Next.js App Router: a Server Component renders with the server key async function getPageData(slug) { const response = await fetch("https://api.foir.dev/graphql", { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": process.env.FOIR_SERVER_KEY, }, body: JSON.stringify({ query: `query GetPage($slug: String!) { page(naturalKey: $slug) { _id } }`, variables: { slug }, }), }); return response.json(); }

Client-Side Key Safety

If you need to use API keys in client-side code:

  1. Use a publishable key only (foir_pub_)
  2. Restrict the key to the models it needs, so a leaked key reaches nothing else
  3. Monitor usage in the console

Key Rotation

Rotation is additive, so it needs neither a second key nor a maintenance window. Rotating issues a new secret and moves the outgoing one into a previous slot, where it keeps authenticating for 24 hours:

  1. Rotate the key — in the dashboard, or foir api-keys rotate <id>
  2. Deploy the new secret
  3. Once it is live, end the old one with foir api-keys retire-previous <id>

Both secrets belong to the same key, so they share its scopes, model limits and organization confinement exactly. Creating a second key instead gives you a second row with its own id and its own reach to keep in step by hand, which is the thing this replaced.

A key holds at most two secrets: rotating again inside the window ends the older one at once.

If you are rotating because a secret leaked, retire the previous secret straight away. Rotation on its own leaves it valid for another 24 hours. To end every secret immediately, revoke the key rather than rotating it.

Rotating changes a key’s secret. Renewing an admin key is the other thing: it moves the key’s expiry and keeps its secret, so nothing that holds the key needs changing. See An admin key expires.

See the CLI reference for the commands.

Troubleshooting

UNAUTHENTICATED Error

{ "errors": [{ "message": "API key or a signed-in person's token required", "extensions": { "code": "UNAUTHENTICATED" } }] }

The request carried no x-api-key header, and no signed-in person’s token that verifies.

A key that is sent and does not authenticate is answered differently. An admin key past its expiry is told so, with the date, once its secret has matched: This API key expired on 10 January 2027. Renew it, or make another (https://docs.foir.dev/credentials). Every other key that does not authenticate is told Invalid or expired API key and nothing of why.

PERMISSION_DENIED Error

{ "errors": [{ "message": "missing required scope: records:write:order", "extensions": { "code": "PERMISSION_DENIED" } }] }

Common causes:

  • A write the caller’s scopes do not cover: a visitor who is not signed in on a publishable or a server key, or a signed-in user whose role does not grant it
  • A sign-in, or a user’s token, sent through an admin key: nobody signs in through one
  • A server key or an admin key sent from a browser
  • A write to a record that already exists by a caller that cannot read its model. See Changing a record takes reading it

A user’s token that has expired or doesn’t verify is not refused. The request is served as nobody, and the response says so: see When a user token is rejected.

A request whose API key simply lacks the required scope is rejected with the message missing required scope: <scope> (e.g. missing required scope: records:write, or missing required scope: operations:execute:<operation-key> for a per-operation-restricted key). Where the caller has nobody signed in and the key holds the permission without giving it, the message goes on in brackets: missing required scope: records:read (this key holds it and gives it to nobody who is not signed in: ...). The permission’s name always comes first and is followed by a space or the end of the message. It carries PERMISSION_DENIED. It refuses one field rather than the request, so it comes back with HTTP 200 and the rest of the response beside it.

Cannot query field

Cannot query field "executeCheckout" on type "Mutation"

A field your query names doesn’t exist in the schema this key sees. Restricted keys get a pruned schema: per-operation scopes remove unlisted execute<Op> mutations, a model allow-list removes unlisted models’ typed fields, the generic record fields and the embeddings fields, and publishable keys never see write fields. If the field works with one key and not another, compare the two keys’ scopes and restrictions in the dashboard — and regenerate any codegen artifacts against the key your app actually ships with.

Organization Selection Errors (X-Org-Id, X-Org-Url)

A request naming an organization with X-Org-Id or X-Org-Url is rejected when:

  • 404 — organization not found: the id is not an active organization of this key’s project, or no active organization’s address covers the URL. One answer whether it is unknown, suspended, pending deletion or another project’s.
  • 403 — X-Org-Id names an organization other than the one this credential is confined to: the key is confined to an organization and may only name its own. Drop the header, or use the project key.
  • 400 — X-Org-Id and X-Org-Url name different organizations: send one, or two that agree.

A user token that is not accepted

A user’s token sent beside a key is never refused. One that has expired, was revoked, or belongs to another project is dropped, the request is served as nobody, and extensions.auth and the X-Foir-Auth-Downgraded header say why. Refresh the token when the reason is expired. See When a user token is rejected.

Last updated on