The Data Client
@foir/sdk/data is a typed client for your project. It sends a GraphQL document to your API (the same executor, the same scope checks and the same response cache as every other consumer) but you never write one. The document is printed from the selection tree your project publishes for that operation.
const page = await foir.page.findUnique({ naturalKey: 'home' });What you get over writing the document yourself: no .graphql files, no graphql-codegen step, and no graphql dependency in your bundle — this subpath imports neither graphql nor @graphql-typed-document-node/core, because printing a resolved tree is string building.
A field reaches your app when you regenerate, not when it is added
This is the one thing to understand before anything else on these pages, because it is the only place the client’s behaviour is not what you would guess.
Every operation is complete by default: it selects every scalar on the model, so your generated interface is unconditionally true about the record you get back. That completeness is resolved at build time, from the selection trees foir types writes into your project.
So when a field is added to a model — in the dashboard, in a migration, in someone else’s branch — it does not join your responses on the next request. It joins them on your next foir types plus a deploy. Until then the document your client prints is the one the old schema described, and the new field is not merely untyped: it is not requested.
# a field was added upstream. this is the step that picks it up.
npx foir types --out src/foir.generated.tsThat is deliberate. A selection your build owns is a selection you can diff and review, and a payload that grows because someone else shipped a field is a payload nobody chose. It also means foir types belongs in the same place your other codegen does — committed, and re-run when the schema moves.
The generated module records the surface it came from. foir types --check compares it with the served surface in CI, and a client built with checkSchemaDrift: true tells you when you have fallen behind, naming what moved:
[foir] schema drift: the types were generated from surface 5b0c9f3e1d2a4c6e8f7a9b1c3d5e7f90,
and the server is serving c4e1a7b90d2f3e5a6b8c9d0e1f2a3b4c (published). Changed since:
model `page`. Everything the generated module describes is still served as generated, so
every typed call keeps working. The surface has grown: re-run `foir types` to pick up what
is new, because a field added since is not merely untyped, it is not requested.A manifest carries two versions, and your client is pinned to only one of them. schemaVersion is the server’s invalidation counter: every write that could change a response moves it, including pushing an operation, a role or a key, and it is what the ETag and the response cache key on. surfaceVersion is a hash over exactly the parts of the manifest foir types reads, so it moves if and only if regenerating would write a different file, and it is what the generated module records and the drift check compares. So a push that changes nothing your client prints is never drift, a field published on a model your types include always is, and every drift the client reports is real. The remedy is foir types.
Drift does not stop a call. A surface that has grown still answers every document your module prints, so the client reports the drift and keeps working. It refuses a typed call only when something that call depends on is no longer served the way the module describes it: a field its selection names, its op, or one of its arguments. See refusing a call the server can no longer answer.
The client’s check is off unless you ask for it, because it reads the manifest once per client and a cold start builds a new client every time. Asked for, it runs once per client instance, is never awaited, and never rejects into your app. See schema drift for how to route it somewhere useful, and for checkFoirSchemaDrift, which asks at a moment you choose.
Install
The client ships in the already-published SDK package. There is no new required peer dependency.
npm install @foir/sdkQuickstart
1. Get an API key
Create one in the dashboard under Settings > API keys. Your app’s key is a publishable key (foir_pub_). With nobody signed in it does what the key gives: the list under What anyone can do without signing in, where a new key’s reads are ticked to begin with and nothing is given that is not ticked. A signed-in user’s bearer adds what their role grants. See a key’s two lists. An operation’s endpoint uses no key at all, a server that renders your pages holds a server key (foir_srv_), and an admin key (foir_adm_) is only for a machine of your own. See Credentials.
The key is not just authentication here. It determines the shape of the client: the operations available on foir are exactly the operations that key is allowed to perform, enforced at compile time. See per-key shaping.
2. Generate types
The generator ships in the Foir CLI:
npm install -D @foir/cli
npx foir types --out src/foir.generated.tsThis reads GET /v1/manifest, the per-caller description of your project, and writes one module holding your interfaces, the selection tree behind each operation, and the surface version they came from. Commit the result: it is a deterministic build input, and CI should not need a network call to your project.
The full flag list is foir types --help. --out, --api-key, --channel and --check are the ones you are likely to want; --check writes nothing and exits non-zero when the committed file differs from a fresh generation, which is what you want in CI.
3. Create the client
import { createFoirClient } from '@foir/sdk/data';
import * as generated from './foir.generated';
export const foir = createFoirClient({
apiUrl: 'https://api.foir.dev',
apiKey: process.env.PLATFORM_API_KEY!,
generated,
});One import and one call. The module carries both halves of what foir types wrote: the FoirSchema type, which erases at build, and the selection trees and surface version, which are values the client prints documents from and checks drift against. So the type parameter is inferred rather than restated, and there is no list of exports to keep in sync at the call site.
Pass it whole or do not pass it: a module missing one of those exports is a compile error naming it. That is deliberate. The individual fields still exist (surfaceVersion, surfaceHashes, selections, namespaceSelections, selectionUnions) and still win where both are given, but a subset was always a mistake, and it used to turn into a silent manifest fetch instead of an error.
If your environment already follows the PLATFORM_API_URL / PLATFORM_API_KEY convention used by @foir/sdk/client, createFoirClientFromEnv(env, { generated }) reads the credentials for you.
4. Query
This is the document that goes on the wire:
query CostBreakdownFindUnique($id: String) {
costBreakdown(id: $id) {
_createdAt _hasDraft _id _modelKey _naturalKey _ownerId _ownerKind
_resolvedBy _segments _updatedAt _variant
baseColor
collab { enabled roomName wsUrl }
currencySymbol
heading
quantity
salesPrice
sections { cost label }
subline
}
}You do not write it. This is what you write, and the client prints the rest:
const cost = await foir.cost_breakdown.findUnique({ id: 'kx41m0e8kbmy4ftbjyh0svqe' });And this is what you get back, which is the half you cannot infer from the call:
{
"_createdAt": "2026-05-19T09:14:22.104831Z",
"_hasDraft": null,
"_id": "kx41m0e8kbmy4ftbjyh0svqe",
"_modelKey": "cost_breakdown",
"_naturalKey": "jacket-cost",
"_ownerId": null,
"_ownerKind": null,
"_resolvedBy": null,
"_segments": null,
"_updatedAt": "2026-05-19T09:31:07.552019Z",
"_variant": null,
"baseColor": "#1d1d1f",
"collab": {
"enabled": true,
"roomName": "cost_breakdown:kx41m0e8kbmy4ftbjyh0svqe:default",
"wsUrl": "wss://realtime.foir.io"
},
"currencySymbol": "£",
"heading": "What it costs",
"quantity": 1,
"salesPrice": 495,
"subline": "Made in England, priced in the open.",
"sections": [
{ "cost": 182, "label": "Materials" },
{ "cost": 96, "label": "Cut and make" }
]
}Every scalar is present and no field is optional, which is exactly what makes CostBreakdown a type you can trust. Selection and Responses covers what that costs and how to narrow it.
If you skip step 2
The client still works. With no selections passed, it fetches GET /v1/manifest once at first use and reads the same trees off it.
That is a fallback, not the fast path, and the difference is a round trip in front of your first query on every cold start — to learn something a generated file already knows. It exists so a REPL, a script or a first five minutes with the client does not need a build step. Anything you deploy should pass the generated trees.
Credentials
The client is built from one of the three credential classes Foir has (Authentication):
| Credential | Held by | Client |
|---|---|---|
Publishable key (foir_pub_), plus the user’s own bearer when someone is signed in | Your app in a browser or a mobile app | apiKey and bearerToken |
Server key (foir_srv_), plus the user’s own bearer when someone is signed in | A server rendering your pages | apiKey, bearerToken and visitor |
| Dispatch token | An operation’s endpoint | dispatch, and no key |
Admin key (foir_adm_) | A machine of your own: integration sync, CI seeds, config push, back-office tooling | Not this client: createServerClient from @foir/sdk/server |
Your app’s client is the publishable key, with the signed-in user’s own bearer. The bearer is a string or a function resolved before every request, so a cookie session can be read per request; with no user signed in, return null and the client reads as a visitor:
const foir = createFoirClient({
apiUrl: 'https://api.foir.dev',
apiKey: process.env.PLATFORM_API_KEY!, // your app's publishable key
generated,
bearerToken: () => getUserToken(session),
});Inside an operation’s endpoint the client is built from the dispatch token the endpoint was handed, and calls Foir as the operation, with the grants it declared and the user who ran it. It takes no key, no bearer and no organization, and its generated module comes from foir types --operation <key>:
const { dispatch } = await requireScopedToken(request, { expectedProjectId });
const foir = createFoirClient({ apiUrl, dispatch, generated });An admin key is never your app’s credential, and createFoirClient refuses one when the client is created. Anything your app does for a user beyond what their role lets them do themselves is an operation. See App architecture. The key your rendering server holds is a server key, below.
A server rendering your pages
A server that renders pages calls Foir for every visitor from one address, its own. The public API limits each visitor of a site within the key, so a server has to say which visitor each call is for, or every page it renders counts as one visitor. Its address is also where the server is, and not where the visitor is, so a variant targeted by country or location would be chosen for your host’s data centre. Saying who and where the visitor is is a permission, visitors:forward, and a publishable key cannot hold it: it is public, so anyone holding one could name any address and take a fresh allowance on every request. A server key can.
So the rendering server uses its own server key. It gives a visitor what your publishable key gives (the reads, and operations:execute:<op> for any live field a page renders), and it holds visitors:forward. It sends the signed-in user’s bearer as the browser would, and a request carrying one is that user acting as themselves: their role, beside what the key gives. It says who and where the visitor is in visitor:
const foir = createFoirClient({
apiUrl: 'https://api.foir.dev',
apiKey: process.env.FOIR_SERVER_KEY!, // foir_srv_, holding visitors:forward
generated,
bearerToken: () => getUserToken(session),
visitor: () => visitorOf(request), // see the table below
});visitor is the visitor your server is calling for, or a function returning them for each request. A string is their address alone. An object says where they are too:
// Vercel
import { geolocation, ipAddress } from '@vercel/functions';
function visitorOf(request: Request) {
const geo = geolocation(request);
return {
address: ipAddress(request),
country: geo.country,
latitude: Number(geo.latitude),
longitude: Number(geo.longitude),
};
}- The address is sent as
X-Foir-Visitor-IP, and the per-visitor limit, the sign-in limits and the anonymous note quota are kept by it. - The country and the coordinates are attached to every read, in
contexts.countryandcontexts.location, so a variant targeted by country or location is chosen for the visitor. Coordinates are sent at two decimal places, about a kilometre. Latitude and longitude go together or not at all. - The visitor is resolved once for a request, so the header and the read name the same one.
Through a key holding visitors:forward, Foir never uses where the caller is. A read that says no country and no coordinates is answered as a visitor nobody could place, wherever your server runs.
Give it what your host guarantees: the values its edge sets and a visitor cannot. A request header a visitor can write, such as an X-Forwarded-For your host passes through, lets anyone name a fresh address per request, which is exactly what the limit exists to stop. The SDK does not read any of them for you, because which values are trustworthy depends on your host.
| Host | The visitor’s address | Country | Latitude and longitude |
|---|---|---|---|
| Vercel | ipAddress(request) from @vercel/functions, or the x-real-ip header, which Vercel sets and does not take from the visitor | geolocation(request).country from @vercel/functions | geolocation(request).latitude and .longitude, which are strings: pass them through Number() |
| Cloudflare Workers | the CF-Connecting-IP header, which Cloudflare sets | request.cf.country | request.cf.latitude and request.cf.longitude, which are strings: pass them through Number() |
| Netlify Functions | context.ip | context.geo.country.code | context.geo.latitude and context.geo.longitude |
| Shopify Oxygen | the oxygen-buyer-ip header, which Oxygen sets | the oxygen-buyer-country header | the oxygen-buyer-latitude and oxygen-buyer-longitude headers, through Number() |
| Node (Express) behind your own load balancer | req.ip, with trust proxy set to that load balancer and nothing wider | whatever your load balancer or your own lookup gives, or nothing | the same |
A reading your host could not make is left out: a missing country is not sent, and a coordinate that is no number is no location.
A function that returns nothing sends nothing, and the call counts as your server’s own. A value the API cannot read as one address is refused, naming the header, and a country that is not two letters or a coordinate out of range is refused, naming the field, so a mistake shows up the first time it happens. A key without visitors:forward is refused the header and the two fields, naming the permission, and a client built from a publishable key is refused visitor when it is created.
What a visitor submits (a form, an operation open to anonymous callers) can go from the browser on your publishable key, where the browser already calls as its visitor. It can also go through your server, where the server key gives the same create or operation.
A server key’s reads go to POST /graphql. A publishable key’s reads of published content, with nobody signed in and no organization named by a header, go to the shared endpoint, GET /cdn/graphql, where the CDN in front of the API can answer a repeat without it reaching Foir. On Foir’s own API host that is Cloudflare; on your own API domain it is your CDN, and whether it stores these reads is its setting. Everything else the client sends, a server key’s reads included, goes to /graphql, and the API’s own response cache still answers those.
Addressing
Three shapes, because the client has no runtime schema to disambiguate them with:
| Call | For |
|---|---|
foir.<model>.<op>(…) | Your models — page, post, product |
foir.ns.<namespace>.<op>(…) | Root surfaces with no model behind them — search, notifications, users |
foir.raw(document, variables?) | A GraphQL document you wrote yourself |
Model keys are used verbatim, exactly as the manifest lists them. A model keyed cost_breakdown is foir.cost_breakdown, not foir.costBreakdown — the key is what resolves the operation, so renaming it for aesthetics breaks the call.
Operation names are the canonical ones (findUnique, findMany), not the GraphQL root field (costBreakdown, costBreakdowns). The two differ and only the first is addressable here.
ns, raw and dispose are reserved. A model keyed one of those would collide.
The client is shaped by your key
GET /v1/manifest returns only what your credential may do, and your types are generated from it — so an operation your key cannot perform is not on the type at all:
// Types generated from a publishable key:
await foir.post.findMany({ first: 10 }); // fine
await foir.post.create({ input: { title: 'Hi' } });
// ~~~~~~
// Property 'create' does not exist on type …That is a compile error, not a runtime 403. Types generated for a credential that may make the call have it: foir types --operation <key> for an operation’s endpoint, which is where your app’s own writes belong.
The server enforces this independently — the types are a convenience, not the boundary. The same call made through foir.raw() is rejected by the executor on scopes, exactly as it would be from any other client.
Real-time
Subscriptions are part of the same client, over the same credential. foir.page.onChange(…) and the rest are covered in Subscriptions; nothing extra is installed, because the SDK speaks the graphql-transport-ws protocol itself.
Writing your own documents
@foir/sdk/client is the other half of the package and is staying: a small typed GraphQL request function for consumers who want to author documents themselves, with graphql-codegen for types. Use it when you want several root fields in one round trip, a fragment library, or field-level control the generated client’s selection verbs do not reach.
The two share the endpoint, the credentials and the environment variables, so mixing them costs nothing:
import { createFoirClient } from '@foir/sdk/data';
import { foirRequest } from '@foir/sdk/client';
// Typed reads for application code
const page = await foir.page.findUnique({ naturalKey: 'home' });
// Your own document where you want the control
const { data } = await foirRequest(HomepageBundleQuery, { slug });foir.raw(document, variables?) is the same escape hatch without the second import — see the operation reference.
Where these examples come from
The worked examples on these pages (the printed documents, the generated types and the response key sets) come from one project’s manifest. The CLI’s own tests generate that project’s types from it on every run, so the interfaces and renamed keys quoted here cannot drift from what foir types emits.
The models are page, which reaches a Block union through pageContent.sections, and cost_breakdown. Field names, renamed keys and key sets are that project’s. The values are illustrative.
Next
- Generating Types — the manifest, the generated module, and drift
- Selection and Responses — complete-by-default,
pick,omit,include, and unions - Operation Reference — every operation, per model and per namespace
- Subscriptions — live data over the same client
- Error Handling — the real error shapes and what causes them
- Preview, Drafts and Edge — draft content and edge-runtime constraints
- Choosing an API Style — generated calls or your own documents