Client
Typed JavaScript client for the CMS REST API.
@cms/client is a lightweight fetch wrapper for the CMS API. It works in any JavaScript runtime — browsers, Node, Deno, edge workers, and SSR frameworks.
Setup
import { createClient } from "@cms/client";
import type cmsConfig from "./cms.config";
const cms = createClient<typeof cmsConfig>({
url: "https://cms.example.com",
token: "your-api-key",
});
Pass your config as a type-only generic. The runtime never touches the config object — only its type informs the client — so secrets and server-only SDKs (Shopify, etc.) stay out of the bundle. Entity names become a checked union on every method, and responses are inferred from the selection you pass.
Options
| Option | Type | Description |
|---|---|---|
url |
string |
Where the CMS runs (required). The client adds /api to every path |
token |
string |
API key (cms_k_…) or session token (cms_s_…), sent as Authorization: Bearer |
headers |
Record<string, string> | () => Record<string, string> |
Custom headers (static object or function) |
credentials |
RequestCredentials |
Fetch credentials mode (e.g. "include" for cookies) |
fetch |
typeof fetch |
Custom fetch implementation |
signal |
AbortSignal |
Default abort signal for all requests |
logger |
boolean | ClientLogger |
Request log. On by default outside browsers, off in browsers. false disables it — see Logging and metrics |
onRequest |
(event: ClientRequestEvent) => void |
Called once per request, success or failure — for metrics and tracing |
Typing responses
Reads are types-only — there’s no per-call generic or Zod schema. The response type is computed from the entity name and the inline selection you pass:
const { data: post } = await cms.find("posts", {
fields: { title: true, status: true },
resolve: { author: { name: true } },
});
// ^? { id: string; title: string; status: ...; author: ... } | null
fieldsnarrows the root columns (omit it to return all).resolvewidens relations, replacing the bare{ id, _entity }reference with the resolved object.
The client trusts the server response and never validates at runtime. See Selecting fields and Resolving relations below for the full selection grammar.
Extracting a named type
To name the response type of a specific query, use DocOf from @cms/client. It takes your config type, the entity name, and an optional selection — and unlike a plain schema-based helper, it also includes _translations? for translatable entities:
import type { DocOf, EntityName, Selection } from "@cms/client";
import type { CmsRootConfig } from "./types";
const pageResolve = {
blocks: { hero: { image: { url: true } } },
} as const;
type ResolvedPage = DocOf<CmsRootConfig, "page", { resolve: typeof pageResolve }>;
In a project with many queries, bind the config once and re-export a two-parameter alias:
// src/lib/cms/types.ts
import type { DocOf, EntityName, Selection } from "@cms/client";
import type { InferEntitiesSchema } from "@cms/config";
export type CmsRootConfig = typeof import("~/cms.config").default;
export type CmsSchema = InferEntitiesSchema<CmsRootConfig>;
export type CmsResult<
Name extends EntityName<CmsRootConfig>,
Sel extends Selection<Name, CmsSchema> | undefined = undefined,
> = DocOf<CmsRootConfig, Name, Sel>;
Then every query file uses the shorter form:
import type { CmsResult } from "@/lib/cms/types";
type ResolvedPage = CmsResult<"page", { resolve: typeof pageResolve }>;
type FullPage = CmsResult<"page">; // no Sel → all fields, relations unresolved
Methods
find
Returns the first record matching the query, or null.
find(name, params?): Promise<{ data: Doc | null }>
const { data: post } = await cms.find("posts", {
filter: { slug: { $eq: "/hello-world" } },
fields: { title: true, slug: true },
});
list
Returns a paginated list of records.
list(name, params?): Promise<{
data: Doc[];
meta: { total: number; limit: number; offset: number };
}>
const { data: posts, meta } = await cms.list("posts", {
filter: { status: "published" },
sort: ["-publishedAt", "title"],
limit: 10,
offset: 0,
});
get
Returns a single record by ID (collection) or the singleton value (global).
// Collection — by ID
get(name, id, params?): Promise<{ data: Doc }>
// Global — no ID
get(name, params?): Promise<{ data: Doc | null }>
// Collection
const { data: post } = await cms.get("posts", "some-uuid");
// Global
const { data: settings } = await cms.get("settings");
// Global with locale
const { data: settings } = await cms.get("settings", { locale: "pt" });
With a typed client the two shapes don’t mix: get("settings", id) and get("posts") are type errors, and so are create and delete on a global. The same split applies to every method with an id and a no-id form (update, drafts.*, versions.*, unpublish). CollectionName<typeof config> and GlobalName<typeof config> name each side for helpers of your own.
Collection and global get results always carry document metadata (_status, _draftCreatedAt). Pass draft: true to fetch the editorial view (canonical merged with the pending draft).
create
Creates a new record. The body is typed from the entity’s config — its schema input minus the engine-managed columns (id, createdAt, …).
create(name, body, params?): Promise<{ data: Doc }>
const { data: post } = await cms.create("posts", {
title: "New post",
status: "draft",
});
update
Updates an existing record by ID (collection) or upserts the singleton (global).
The patch is a shallow Partial of the create body — send only the fields you want to change.
// Collection — by ID
update(name, id, body, params?): Promise<{ data: Doc }>
// Global — no ID
update(name, body, params?): Promise<{ data: Doc }>
// Collection
const { data: post } = await cms.update("posts", "some-uuid", {
status: "published",
});
// Global
const { data: settings } = await cms.update("settings", {
siteName: "New name",
});
delete
Deletes a record by ID and returns its id. Globals can’t be hard-deleted — use drafts.discard or unpublish.
delete(name, id, params?): Promise<{ data: { id: string } }>
await cms.delete("posts", "some-uuid");
route
Calls one of your custom routes (/custom/<name>) or a
plugin’s (/plugins/<instance-name>/<route>), typed
from your config: the path completes from it, query and body are typed from the route’s
schemas, and the result is what its handler passes to routeJson(), as JSON delivers it (a Date
becomes a string).
route(path, options?): Promise<Data>
| Option | Type | Description |
|---|---|---|
method |
"GET" | "POST" | ... |
Default "GET". Required unless the call is a GET, and limited to the methods the path has |
query |
The route’s query schema input |
Sent as the query string, as given (unlike entity calls, fields or sort aren’t rewritten). Required when the route declares a schema |
body |
The route’s body schema input |
Sent as JSON. Required when the route declares a schema |
signal |
AbortSignal |
Cancels the request |
const { data } = await cms.route("/plugins/redirects/resolve", { query: { path: "/old-page" } });
// data: { to: string; status: number }
await cms.route("/custom/contact", { method: "POST", body: { email, message } });
An unknown path, a method the path doesn’t have, or a missing or mistyped query or body is a
type error. query may be left out only when the schema accepts {}, which is what the engine
parses a missing query string to; body only when the schema accepts undefined. A non-2xx answer throws ClientError, including the engine’s
400 VALIDATION_ERROR when the route’s schema refuses the input.
What stays loose:
- A route whose handler returns a plain
Responseinstead ofrouteJson()resolves tounknown. - Routes or plugins declared outside
config()(aRouteDef[]list built beforehand) accept any/custom/...path, withunknownresults. - A plugin that doesn’t declare its instance name types its routes under any name,
/plugins/${string}/<route>. See Plugins → Contributions. - An untyped client (
createClient()with no generic) accepts any custom or plugin path.
The response isn’t validated at runtime; it’s typed from the handler at compile time.
request
Low-level method for any path under /api, untyped. Prefer route for custom and
plugin routes. The client adds /api to the path.
request<T>(path: string, options?: RequestOptions<T>): Promise<T>
| Option | Type | Description |
|---|---|---|
method |
string |
Default "GET" |
params |
Record<string, unknown> |
Query string |
body |
unknown |
Sent as JSON |
signal |
AbortSignal |
Cancels the request |
schema |
z.ZodType<T> |
Validates the answer; the return type follows it |
T is trusted, not checked. Pass schema to validate the answer at runtime.
const { data } = await cms.request<{ data: { to: string; status: number } }>(
"/plugins/redirects/resolve",
{ params: { path: "/old-page" } },
);
// With schema validation
const { data } = await cms.request("/plugins/redirects/resolve", {
params: { path: "/old-page" },
schema: z.object({ data: z.object({ to: z.string(), status: z.number() }) }),
});
Signing in
cms.auth runs the email-code sign-in and manages the caller’s session. It never changes the client’s options: pass a session token to a client of its own.
// 1. Email a login code. Resolves the same way for unknown emails.
const { authRequestId } = await cms.auth.request("ada@example.com");
// 2. Exchange the emailed code for a session token (shown once — store it securely).
const { user, token, expiresAt } = await cms.auth.create({
authRequestId,
code: "123456",
transport: "token",
});
// 3. Act as that user, with their role.
const userCms = createClient<typeof cmsConfig>({ url, token });
await userCms.auth.me(); // { user }
| Method | Returns | Description |
|---|---|---|
auth.request(email, { signup?, locale? }) |
{ authRequestId, resendIn } |
Emails a login code. resendIn is the seconds before another can be requested (a 429 until then). signup: true asks for a signup code (see below). locale is the locale the person is reading in (see below) |
auth.create({ authRequestId, code, transport?, name? }) |
{ user, expiresAt, created, token? } |
Opens a session. transport: "token" returns token and sets no cookie; "cookie" (default) sets the cms_session cookie, for browsers on the CMS’s own site. created is true when a signup code created the user now |
auth.me() |
{ user } |
The caller’s user (id, email, name, role); ClientError 401 without a session (an API key has none). Fields added to _user aren’t included: read them with cms.get("_user", user.id), under the role’s permissions |
auth.refresh() |
{ expiresAt } |
Extends the session to 30 days from now |
auth.logout() |
void |
Ends the session. The client keeps its token option; drop the client |
Signup. When the public role has signup, people without an account can create one. Ask for a signup code; verifying it creates the user with the signup role, or signs in the user the email already has:
const { authRequestId } = await cms.auth.request("new@example.com", { signup: true });
const { user, token, created } = await cms.auth.create({
authRequestId,
code: "123456",
transport: "token",
name: "Ada", // stored only on a new user
});
if (created) {
// first sign-in: onboarding
}
The response is the same whether or not a code was sent (signup off, or refused by signup.allow), so a form can always move on to the code step.
Locale. Pass the locale your site is showing, and the code email is written in it (with an
email.templates.loginCode that writes more than one
language). A signup also stores it as the user’s preferredLocale, for later emails. One the
project doesn’t have is ignored, and the email falls back to the user’s preferred locale, then the
default:
await cms.auth.request(email, { signup: true, locale: "pt" });
On a server, build a client per user. A server renders many visitors at once, so cms.config({ token }) on a shared client would make every request after it act as that user. Create one with createClient({ url, token }) for the request instead.
Refresh yourself. Sessions last 30 days from sign-in or the last refresh(); the client never refreshes on its own. Call auth.refresh() when the app starts or once a day.
Sessions
cms.auth.sessions lists and revokes sessions: your own, or with userId (admins only) anyone’s. The current session can’t be revoked here; auth.logout() ends it.
const sessions = await userCms.auth.sessions.list();
// [{ id, transport, userAgent, createdAt, lastUsedAt, expiresAt, current }]
await userCms.auth.sessions.revoke(sessions[1].id);
await userCms.auth.sessions.revokeAll({ exceptCurrent: true }); // { revoked: n }
// As an admin: sign a user out everywhere
await adminCms.auth.sessions.revokeAll({ userId });
lastUsedAt is updated at most once an hour.
Query parameters
Read methods (find, list, get) accept these query parameters:
| Param | Type | Description |
|---|---|---|
filter |
EntityFilter |
Filter records — see Querying. Typed: the entity’s columns, $or and dotted relation or JSON paths (author.name); any other key is a type error |
sort |
SortInput |
Orderable column, or array of them; - prefix = descending — see below |
fields |
selection | Narrow the root columns — see below |
resolve |
selection | Expand relations — see below |
limit |
number |
Max records to return (list only) |
offset |
number |
Skip N records (list only) |
draft |
boolean |
Make it a draft read (?draft=true); overrides the client-level draft |
locale |
string |
Select a translatable global’s locale row (global get only) |
signal |
AbortSignal |
Abort signal for this request |
Any other key is a type error. If a cast or plain JS lets one through, the method throws before
sending the request, naming the method and the key; a key set to undefined is ignored. For an
engine param the read methods don’t define, use request, which sends every param
as is.
Selecting fields
fields narrows which root columns come back. Omit it to return every column. It’s a flat { column: true } map typed against the entity, and id is always included:
const { data } = await cms.find("posts", {
fields: { title: true, slug: true },
});
// ^? { id: string; title: string; slug: string } | null
A relation must be selected here to be resolvable — resolving a column you dropped from fields is a compile error.
Resolving relations
By default a relation comes back as a bare { id, _entity } reference. resolve is an additive tree that expands relations in place. A relation key takes:
true(or{}) — resolve all of the target’s fields.- a projection object — resolve only the named fields (
idalways included).trueon a JSON field (an object, array or blocks) projects it whole, its relations as references; an object traverses into it. - a nested object — chain into the target’s own relations, or traverse a JSONB object/union to reach a relation inside it.
const { data: post } = await cms.find("posts", {
resolve: {
author: { name: true, bio: true }, // projection
tags: true, // all fields, every tag
hero: { cta: { link: { url: true } } }, // traverse JSONB → resolve `link`
},
});
Blocks (arrays of variants)
A relation inside an array of union variants (a page-builder blocks array) is addressed per variant — key by the variant’s _type:
const { data: page } = await cms.find("page", {
resolve: {
blocks: { hero: { cta: { target: { path: true } } } },
},
});
A single (non-array) union field is unqualified — its relation is addressed directly (resolve: { link: { target: { title: true } } }).
Polymorphic targets
A polymorphic relation resolves across all its targets at once. The result is a discriminated union on _entity; a projected field that exists on only some targets is omitted from the branches that lack it (so narrowing on _entity is required to read it). A target the role can’t read stays a bare reference.
Depth
Relation chains are capped at 2 hops — resolve: { owner: { org: { name: true } } } resolves owner then org, and a third relation hop is a compile error. JSONB traversal (drilling through objects/unions toward a relation) is free and doesn’t count against the cap.
Sorting
sort is typed off the entity’s orderable columns. A bare column sorts ascending; a - prefix sorts descending. Pass an array for a multi-key sort (applied left to right):
await cms.list("posts", { sort: "-publishedAt" }); // single key, descending
await cms.list("posts", { sort: ["-publishedAt", "title"] }); // multi-key
Orderable columns autocomplete (both ascending and -descending). Any string is still accepted — for engine-supported paths the row type can’t name (a relation field like author.name, a JSONB path like body.title) or a sort string built at runtime. Because any string passes, a typo in a known column isn’t rejected — that’s the deliberate trade for the escape hatch. One exception: a literal naming a field stored as JSON (json, richText, object, array, union), such as sort: "-meta", is a type error, because the engine can’t sort by it without a path. Sort by a path inside it instead (meta.order).
Runtime configuration
Use config() to update client options after creation — useful for setting auth tokens dynamically:
const cms = createClient({ url: "https://cms.example.com" });
// Later, after authentication
cms.config({ token });
Only do this on a client one user owns (a browser tab, a native app). On a server, see Signing in.
Logging and metrics
Outside the browser (window is undefined), the client logs one line per request to console — whether it succeeds or fails. In the browser it logs only failed requests, so a broken fetch shows up in devtools without every 200 alongside it:
[cms] GET 200 /api/posts 12.3ms
[cms] GET 404 /api/posts/abc 8.1ms — NOT_FOUND: Document not found (request id 8f2c…)
[cms] GET 403 /api/posts 6.0ms — invalid api key
[cms] GET 502 /api/posts 41.7ms — Bad Gateway, text/html body (12480 bytes), server: nginx
[cms] GET NETWORK_ERROR /api/posts 3.1ms — fetch failed ← connect ECONNREFUSED 127.0.0.1:4000 → http://localhost:4000
[cms] POST TIMEOUT /api/posts 10002.4ms — fetch failed ← Connect Timeout Error [UND_ERR_CONNECT_TIMEOUT] → http://localhost:4000
Each line has the method, the outcome, the path (never the query string, which can carry tokens or filters) and how long the request took. The outcome is the HTTP status, or — when no response arrived — what went wrong:
| Outcome | Meaning |
|---|---|
NETWORK_ERROR |
fetch rejected with a TypeError: connection refused, DNS failure, TLS error, connection reset. |
TIMEOUT |
An AbortSignal.timeout() fired, or the runtime gave up connecting or waiting (undici’s UND_ERR_*_TIMEOUT, ETIMEDOUT). |
ABORTED |
The request’s signal was aborted. |
UNKNOWN_ERROR |
Anything else a custom fetch threw. |
A failed request adds a detail after —:
- No response — the error’s message and its
causechain (with error codes such asECONNREFUSED), then→the origin the client tried to reach. - An API error —
CODE: messagefrom the engine’s error body, plus the request id. - Any other answer (a proxy, a gateway, an auth layer) — a short plain-text or JSON body is quoted as is; a long or HTML body is described by its status text, content type, size and
serverheader instead. A short text body also becomes the thrownClientError’s message. - A 2xx that couldn’t be read (a body that isn’t JSON, a
schemathat rejected it) — the error’s message and the response description.
Email addresses and URL credentials in the detail are redacted. For every failure except an API error answer, the error itself is passed to the logger as a second argument, so console prints its stack and causes.
The level follows the outcome: info for 2xx/3xx, warn for 4xx, error for 5xx, failures without a response and 2xx bodies that couldn’t be read.
createClient({ url, logger: false }); // never log
createClient({ url, logger: true }); // log every request to console, browser included
createClient({ url, logger: pino() }); // any object with info/warn/error
Like other options, logger can be changed later with cms.config({ logger: false }).
Metrics
onRequest receives every finished request as a ClientRequestEvent, in every runtime:
type ClientRequestEvent = {
method: string; // "GET", "POST", …
path: string; // e.g. "/api/posts/abc" — includes any base-URL path prefix, no query string
status?: number; // absent when fetch itself failed
durationMs: number;
error?: unknown; // set when the request threw
cacheTags?: string[]; // the response's Cache-Tag, when the CMS sets one (cacheTags config)
};
It runs whether or not logging is on, and an exception thrown inside it (or a rejected promise, if it’s async) is swallowed, so a broken metrics backend never fails a content request. To record a prom-client histogram:
import { createClient } from "@cms/client";
import { Histogram } from "prom-client";
const cmsRequestDuration = new Histogram({
name: "cms_client_request_duration_seconds",
help: "Duration of CMS API requests",
labelNames: ["method", "entity", "status"],
});
export const cms = createClient({
url: process.env.CMS_URL,
token: process.env.CMS_API_KEY,
onRequest: ({ method, path, status, durationMs }) => {
cmsRequestDuration.observe(
{
method,
// "/api/posts/abc" or "/cms/api/posts/abc" → "posts"
entity: path.match(/\/api\/([^/]+)/)?.[1] ?? "",
status: status ? String(status) : "error",
},
durationMs / 1000,
);
},
});
Don’t use path itself as a label: it contains document IDs, so every document would create a new time series. Use a bounded value such as the entity name, as above.
The same hook works for tracing or browser monitoring (RUM).
Page cache tags
With cacheTags on, every published read carries the tags of what it holds. A site’s server can gather them for the page it renders and set them on its HTML, so purging a document evicts the pages that show it. @cms/client/server has a collector for that. It runs on Node’s AsyncLocalStorage, so it lives in its own server-only entry point and browser bundles never pull it in.
import { createClient } from "@cms/client";
import { createTagCollector } from "@cms/client/server";
// The CMS config's `cacheTags.prefix`, exactly; omit it if the CMS uses `cacheTags: true`.
export const pageTags = createTagCollector({ prefix: "site:" });
export const cms = createClient({
url: process.env.CMS_URL,
token: process.env.CMS_API_KEY,
onRequest: pageTags.onRequest,
});
| Call | Does |
|---|---|
pageTags.run(handleRequest) |
Scopes one incoming request: the tags of every read made while handleRequest runs belong to it. Concurrent requests never mix their tags. |
pageTags.onRequest |
Pass it as the client’s onRequest, or call it from your own onRequest with each event. |
pageTags.add(...tags) |
Adds tags for content from other sources, such as a Shopify product. Purging them is your code’s job, e.g. from the source’s webhooks. |
pageTags.header() |
The scope’s Cache-Tag value, each tag once, or undefined when no value under 8 KB covers the page (don’t cache it). |
header() keeps the value under 8 KB, the same limit as the engine. Past it, the CMS’s document tags (<prefix>d:<id>) are dropped, and its entity tags and every tag you passed to add() stay, even one that looks like a document tag: a publish of any document of those entities then purges the page. If the entity tags and your own still overflow, header() returns undefined: dropping any of them would leave a change that never purges the page, so don’t cache it. Send Cache-Control: private, no-store (or skip your s-maxage) on that response. The prefix must be the CMS’s cacheTags.prefix: with another one, the collector can’t tell the CMS’s document tags from yours and drops none of them. Outside run, tags are ignored and header() is empty.
Only reads the client actually sends are seen. A cache you keep in front of the client (an in-process read cache, a memoized fetch) must store each read’s tags with it and pass them to add when it answers from the cache, or the page misses them. A per-request TanStack Query client on the server needs nothing: each render starts empty.
See Tagging the site’s pages for a TanStack Start middleware that sets the header.
Error handling
Failed requests throw a ClientError with structured error data:
import { ClientError } from "@cms/client";
try {
await cms.get("posts", "bad-id");
} catch (error) {
if (error instanceof ClientError) {
console.log(error.status); // HTTP status code
console.log(error.code); // Error code (e.g. "NOT_FOUND")
console.log(error.message); // Human-readable message
console.log(error.details); // Optional additional details
}
}
Previous
REST API
Next
Field types