Skip to Content
API ReferenceData Client (SDK)Preview, Drafts & Edge

Preview, Drafts & Edge

Draft content

Two different things are called “draft”, and mixing them up is the usual cause of “my new field isn’t there”:

Selected byNeeds
Draft schema channelX-Foir-Schema-Channel: draftdrafts:read scope
Draft record contentpreview: true argumentdrafts:read scope

The schema channel decides which shape of your project the server compiles against — whether a model or field you pushed but have not published yet exists at all. The preview argument decides which version of a record you read.

You usually want both. Both take a key holding drafts:read, and that key is a preview environment’s own key: the deployment your team reviews drafts on has a publishable key of its own that holds the scope (or a server key, where a server renders it), and the key your production app ships does not (Preview Mode Access). Anyone who can load the preview environment reads your drafts, so keep it where your team works.

import * as generated from './foir.draft'; const foir = createFoirClient({ apiUrl: process.env.PLATFORM_API_URL!, apiKey: process.env.PLATFORM_PREVIEW_API_KEY!, // the preview environment's own key, holding drafts:read channel: 'draft', generated, }); const page = await foir.page.findUnique({ naturalKey: 'homepage', preview: true });

channel: 'draft' sets the header on every request from that client, including its manifest fetches — so your drift check compares against the draft schema too. A draft-channel client never takes the shared read lane, since draft content is not public.

Note: A publishable or a server key without drafts:read that sends the header is served the published copy rather than refused: GET /v1/manifest with X-Foir-Schema-Channel: draft and a production publishable key returns "channel": "published". It fails open, quietly: if drafts are not appearing, check that the key holds drafts:read first. An admin key without the scope is refused with a 403.

Generate a second module from the draft channel if you are building against unpublished models. This matters more than it looks: the generated selection is what the client asks for, so a field that exists only on the draft schema is not merely untyped — it is not in the document, and the server has nothing to return it in response to.

npx foir types --channel draft --out src/foir.draft.ts

From the environment

createFoirClientFromEnv follows the same convention @foir/sdk/client uses, so a storefront already wired for GraphQL needs no second set of variables:

export const foir = createFoirClientFromEnv(env, { generated });
Variable
PLATFORM_API_URLAPI origin. A trailing /graphql is stripped, so the conventional value works as-is
PLATFORM_API_KEYThe default key
PLATFORM_PREVIEW_API_KEYUsed instead when FOIR_PREVIEW=true: the preview environment’s own key, holding drafts:read
FOIR_PREVIEW'true' selects the preview key and channel: 'draft'

Preview is selected at the environment level, not per request — every loader sees the same view of the world. Load a preview env file for a preview deployment; do not try to flip it per request.

Edge runtimes

The client targets the runtimes the SDK already supports — Hydrogen/Oxygen, React Router loaders, TanStack Start on Cloudflare Workers, Vercel Edge. Three properties make that work, and all three are constraints on the implementation rather than features:

  • fetch only. No Node built-ins anywhere in the import graph.
  • No graphql dependency. This subpath imports neither graphql nor @graphql-typed-document-node/core, so nothing pulls a parser into your worker bundle.
  • No module-level state of any kind. Not a cache, not a flag. A stateless multi-tenant worker serves many projects in one isolate, and anything cached across client instances is cached across tenants.

That last one is why the schema-drift flag is per-instance: a module-level version would let the first project to check silence the warning for every other tenant sharing the isolate.

A bound fetch

Some runtimes hand you a fetch you must use rather than the global — Oxygen’s, or one carrying tracing:

export async function loader({ context }) { const foir = createFoirClient({ apiUrl: context.env.PLATFORM_API_URL, apiKey: context.env.PLATFORM_API_KEY, generated, fetch: context.fetch, }); return { page: await foir.page.findUnique({ naturalKey: 'homepage' }) }; }

Per-request caching

requestInit is merged into every fetch. It is applied after method, headers and body, so those cannot be clobbered by accident.

// Next.js requestInit: { next: { revalidate: 60 } } // Always fresh requestInit: { cache: 'no-store' }

For an AbortSignal you want per call, not per client, build a short-lived client or use foir.raw() — requestInit is client-wide.

Create per request, not per module

The client is a Proxy with no connection state, so constructing one is cheap — it costs an object allocation. On a multi-tenant worker, or anywhere the credential varies, construct it inside the request handler.

A module-level client is fine only when the credential is fixed for the whole deployment. If a bearer token varies per request, pass a function rather than a string and keep the client:

const foir = createFoirClient({ apiUrl, apiKey, generated, bearerToken: () => getSessionToken(), // resolved before every request });

User sessions

The API key resolves the project; a user bearer token adds the identity that self-scoped operations like findMine need. Your app’s key with the user’s own bearer is the user acting as themselves: its publishable key in the browser, its server key on a server that renders your pages.

bearerToken: async () => (await session.get('userToken')) ?? null,

Minting that token — login, registration, refresh, password reset, OAuth callbacks — belongs to @foir/sdk/auth, which owns the part that is actually hard: token storage, refresh scheduling, redirect handling and the React context. It executes on the same surface this client does, so there is one set of credentials and one set of scope checks either way.

So: authenticate with @foir/sdk/auth, then hand the resulting token to the data client. foir.ns.auth.whoami() inspects the credential you ended up with.

Response caching

Every read runs through the same response cache, and the manifest reports each model’s policy:

"cacheControl": { "scope": "PRIVATE", "maxAge": 60 }

An eligible read (a publishable key, no user bearer token, no organization named, a query rather than a mutation, no read-your-writes floor, the published channel) is sent to the shared read endpoint as a GET with the credential and a document hash in the URL, so a CDN in front of you can store the answer. Everything else is a POST. The client makes that decision locally and the server is the authority: it refuses an ineligible request rather than serving it uncached, and a refusal is retried on the ordinary path.

Nothing about the answer differs between the two — same schema, same executor, same auth. See Response Caching.

Last updated on