Config
Complete reference for the cms.config.ts configuration file.
config()
The top-level configuration function:
import { config } from "@cms/config";
export default config({
i18n?: {
locales?: { label: string; value: string }[]; // default: [{ label: "English", value: "en" }]
defaultLocale?: string; // default: first locale's value
};
cors?: {
origins: string[] | "*"; // allowed CORS origins; "*" allows any origin without credentials
};
storage: StorageProvider; // required: localDisk({ root }) or s3({ ... }) from @cms/storage-s3
email?: {
provider?: EmailProvider; // smtp({ ... }) from @cms/email-smtp or ses({ ... }) from @cms/email-ses
templates?: EmailTemplates; // the project's own login code email
};
assets?: AssetsConfig; // upload caps and transform limits, see the Assets guide
database?: { // serving pool timeouts, see Deployment
connectionTimeoutMs?: number; // default: 10000
statementTimeoutMs?: number; // default: 30000
};
auditLog?: { // the record of who wrote what, see below
retentionDays?: number; // default: 90
};
cacheTags?: true | { // Cache-Tag on published reads, see Deployment → CDN caching
prefix?: string; // default: none
};
apiCache?: { // let a CDN cache public published reads; needs cacheTags
sMaxAge: number; // seconds
staleWhileRevalidate?: number;
};
entities: EntityDef[]; // your content entities (including globals)
roles: RoleDef[]; // roles and permissions
admin?: AdminConfig; // admin UI configuration
routes?: RouteDef[]; // project-defined server routes, see below
plugins?: CmsPlugin[]; // optional features, e.g. sentry(), openapi() — see below
});
auditLog
Every write (create, update, publish, draft save, restore, unpublish, discard, delete, bulk
operations, API key changes) adds a row to the _audit_log table: when, the user id and role (no
email), the action, the entity, the document id, its locale, and for updates the names of the
fields the write changed. Values are not stored: versions hold content.
Admins see the log under Settings → Activity: every entry, newest first, filtered by
entity, document, user, action, locale and date range, with the user’s email and name. A
document’s or global’s menu shows that document’s entries in a drawer, with a link to the
filtered list. The API is
GET /api/_audit-log (admins only), with optional entity, documentId, actorId, action,
locale, from and to (ISO date-times, inclusive) query parameters, paged by limit (at most
100, default 50) and offset.
The server deletes rows older than retentionDays at start and then hourly. Rows outlive a
deleted document until then.
cors
Off by default: without cors, the API sends no CORS headers and only same-origin pages (the admin) can call it from a browser.
origins: ["https://example.com", ...]allows exactly those origins, with credentials, so a session cookie works cross-origin.origins: "*"allows every origin without credentials. Browsers send no session cookie, so cross-origin callers authenticate with an API key. The engine logs a warning when this runs in production.
Allowed methods are GET, POST, PUT, DELETE and OPTIONS; allowed request headers are Content-Type and Authorization. Browsers may cache a preflight for 2 hours. Public assets are served with Access-Control-Allow-Origin: * whatever cors says.
storage
Required. A storage provider decides where asset files live:
| Provider | Import | Options |
|---|---|---|
localDisk() |
@cms/config |
root |
s3() |
@cms/storage-s3 |
bucket, region, accessKeyId?, secretAccessKey?, endpoint? |
See Storage for each provider’s options and for writing your own.
Required options take process.env values as is; the provider checks them when the server boots.
Optional. email.provider sends login codes and what server code sends with ctx.email. Without one, they are printed to
the console — fine in cms dev, and cms start warns about it in production.
email: { provider: smtp({ from: process.env.EMAIL_SENDER, hostname: process.env.SMTP_HOSTNAME }) },
| Provider | Import | Options |
|---|---|---|
smtp() |
@cms/email-smtp |
from, hostname, encryption? ("full-tls" default, "starttls", "plaintext-insecure"), port? (defaults from encryption), username?, password? (omit both to skip AUTH) |
ses() |
@cms/email-ses |
from, region, accessKeyId?, secretAccessKey?, configurationSetName? |
A custom provider is a plain object, like a storage provider: { description, create({ logger }) },
where create returns { send({ to, subject, html, text?, from?, replyTo? }) } and lives in a
*.server.ts module. It gets a message the engine has already validated, with html as a
string, and from set only when the message overrides the provider’s own. send must reject when
delivery fails, so a login-code request reports the failure instead of leaving the editor waiting.
See Email credentials.
email.templates
templates.loginCode replaces the login code email (Emails guide). It gets the code and who it’s for, and the
server context, and returns { subject, html, text? }; the engine sends it
to the address that asked. Leave it unset for the default English email.
// emails.server.ts — cms.config is bundled into the admin, so keep templates (and any renderer
// they import) in a *.server.ts module, which the admin build stubs.
import { type EmailTemplates, loginCodeEmail } from "@cms/config";
export const loginCode: EmailTemplates["loginCode"] = (input) =>
input.role.adminPanel
? loginCodeEmail(input) // the default, for editors
: loginCodeEmail(input, { subject: "Your Acme code", heading: "Sign in to Acme" });
// cms.config.ts
email: { provider: ses({ ... }), templates: { loginCode } },
| Input | Type | Description |
|---|---|---|
code |
string |
The six-digit code. |
email |
string |
The address as typed (trimmed). |
expiresInMinutes |
number |
How long the code is valid. |
locale |
string |
The locale to write in, always a configured one: the request’s locale, else the user’s preferredLocale, else the default. |
signup |
boolean |
Whether verifying this code creates the user. |
user |
AuthUser | null |
{ id, email, name, role } of the user signing in; null on a signup. |
role |
RoleDef |
The user’s role, or the signup role on a signup: role.adminPanel tells editors from customers. |
loginCodeEmail(input, copy?) is the default email. copy changes its words and keeps its
layout (subject, heading, expiry(minutes), ignore); a key left out stays English. Copy is
plain text, escaped into the HTML.
The template can’t skip the email: a request that sends no code leaves the person on the code
screen. A throw is logged and reported, and the request fails with a 500, as a failed delivery
does. Without a provider, cms dev prints the rendered email’s text part, so a template can be
tried locally.
requiredEnv
requiredEnv("NAME") from @cms/config reads an environment variable the server can’t run
without, for values no provider checks (the CORS origins, a value your routes need). It returns the
value, or "" when it’s unset, and never throws, so cms build, CI and the admin bundle evaluate
the config without it. cms start and cms dev refuse to boot while any is unset or empty, in one
error with every missing provider option. See
Deployment → Runtime variables in cms.config.
cors: { origins: requiredEnv("CORS_ORIGINS").split(",").filter(Boolean) },
Validation
The config builder validates:
- No duplicate entity names, across your entities and plugins’ (the error names both sources)
- At least one role
_userextensions, yours and plugins’: no field redefines a built-in one or another extension’s, no admin option is set twice, and a required field has adefaultValuedefaultLocaleexists inlocalescors.originsis"*"or a list without a"*"entry- Permission keys reference known entities, plugin entities included
- No entity named
customorplugins(reserved for the/api/customand/api/pluginsprefixes) routesnames, yours and plugins’, match/^[a-z0-9-]+$/and are unique per(name, method)routesrolesentries reference known roles- Plugin instance names match
/^[a-z0-9-]+$/and are unique - Plugin root paths are exact, don’t overlap
/api,/adminor/healthz, and aren’t claimed twice admin.routespaths, yours and each plugin’s, are lowercase segments likereports/monthly, unique per source, and theirrolesreference known rolesadmin.sidebarplaces only pages and plugins that exist. This one is checked when the sidebar is resolved, not insideconfig(): atcms devboot (which fails on it) and in the admin
Built-in entities
These are auto-registered — you don’t define them:
_user— email, name, role (a select of your roles), and with more than one localepreferredLocale(an optional select of your locales: the language emails to the user are written in). Add fields and hooks withentity.extend("_user", …)_image— filename, mimeType, size, width, height, alt, url_video— filename, mimeType, size, width, height, url_file— filename, mimeType, size, url
entity()
import { entity } from "@cms/config";
entity(name: string, {
fields: AnyField[];
title?: string; // human label shown in the admin (sidebar, list header, breadcrumbs)
description?: string; // rendered under the list header
translatable?: boolean; // default: false
global?: boolean; // default: false — singleton mode (see below)
versions?: boolean | { // default: { drafts: false, limit: 50 } — see /guides/drafts
limit?: number | false; // default: 50; false keeps every version
drafts?: boolean; // default: true when versions is set
};
unique?: UniqueRule[]; // values at most one published document may hold — see below
hooks?: EntityHooks;
admin?: {
summary?: EntityAdminSummary;
list?: EntityAdminList;
preview?: (props: { data: TData }) => React.ReactNode;
previewDefaultOpen?: boolean;
bulkActions?: EntityAdminBulkAction[];
};
}): Entity
name is the canonical identifier — it lands in the database, the API, and as the URL slug. title controls the human-readable label shown wherever the admin renders the entity (sidebar item, list page title, breadcrumb). Provide title and description when the bare entity name is too terse or technical for editors.
entity("project-page", {
title: "Project Pages",
description: "Case studies and client work.",
fields: [/* ... */],
});
admin.summary
Controls how documents appear in list views and relation pickers. Declares which fields to fetch and how to render the title, description, and media slots.
const authors = entity("authors", {
admin: {
summary: {
fields: ["name", "bio", "avatar"],
title: ({ data }) => data.name,
description: ({ data }) => data.bio,
media: ({ data }) => data.avatar
? <img src={`/api/assets/${data.avatar.id}`} alt="" />
: <UserIcon />,
},
},
fields: [
text("name", { required: true }),
image("avatar"),
text("bio"),
],
});
| Property | Type | Description |
|---|---|---|
fields |
string[] |
Field names to fetch for list views. Only these fields (plus system fields like id, createdAt) are loaded — the rest are skipped. Fully typed and autocompleted against the entity’s field names. |
title |
string | (props) => ReactNode |
Document title. A string value is used as-is; a callback receives { data } narrowed to the selected fields. |
description |
string | (props) => ReactNode |
Document description. Same format as title. |
media |
string | (props) => ReactNode |
Visual preview. Same format as title. Supports JSX for images, icons, or any React element. |
badge |
string | (props) => ReactNode |
Dashboard badge for recently updated documents. Same format as title. Defaults to the entity’s title when absent — set it when one entity holds several kinds of document. |
When summary is omitted, list views still use a partial fetch. The admin only requests system fields by default, and any fields listed in summary.fields are added to that selection.
Each slot (title, description, media, badge) can be either a static string or a callback. When using callbacks, data is typed as Pick<TData, ...> — only the system fields and the fields listed in fields are available, providing both type safety and editor autocomplete.
admin.list
Controls the table columns rendered in the entity list view. When omitted, the admin falls back to a default layout derived from admin.summary.
const posts = entity("posts", {
admin: {
list: {
fields: ["title", "status", "metadata"],
defaultSort: { field: "createdAt", order: "desc" },
columns: [
{
label: "Title",
sortKey: "title",
render: ({ data }) => data.title,
},
{
label: "Status",
sortKey: "status",
render: ({ data }) => <Badge>{data.status}</Badge>,
},
"createdAt",
],
},
},
fields: [/* ... */],
});
| Property | Type | Description |
|---|---|---|
fields |
string[] |
Field names to fetch for the list view. Same semantics as summary.fields — only these fields (plus system fields) are loaded. |
columns |
(BuiltInColumn | ColumnDef)[] |
Ordered list of columns to render. See column types below. |
defaultSort |
{ field: string; order?: "asc" | "desc" } |
Sort applied on first load when no sort param is present in the URL. field is type-safe: constrained to scalar keys, dotted paths, and "createdAt" / "updatedAt". |
Built-in columns
| Value | Description |
|---|---|
"createdAt" |
Renders the document creation date. Sortable. |
"updatedAt" |
Renders the last-updated date. Sortable. |
"locales" |
Renders locale badges with links to translations. Only visible on translatable entities. |
Custom column definition
{
label: string;
render: (props: { data: TData }) => React.ReactNode;
sortKey?: string; // enables sorting for this column; value is sent to the API as the sort field
}
sortKey is type-safe: accepts scalar keys of TData, dotted paths through object keys (e.g. "metadata.publishedAt"), or the built-in "createdAt" / "updatedAt". Object-typed keys are excluded to prevent sorting on non-scalar values.
admin.bulkActions
An array of custom actions available when documents are selected in the list view. Each action appears as a button in the bulk action bar alongside the built-in Delete action (and Publish / Unpublish when versions: true).
import { StarIcon } from "@phosphor-icons/react";
entity("posts", {
admin: {
bulkActions: [
{
label: "Feature",
icon: StarIcon,
iconOnly: true,
callback: ({ set }) => {
set({ featured: true });
return {
success: (n) => `${n} ${n === 1 ? "post" : "posts"} featured`,
partialSuccess: (ok, fail) => `${ok} featured, ${fail} failed`,
error: "Failed to feature posts",
};
},
},
],
},
fields: [/* ... */],
});
EntityAdminBulkAction
| Property | Type | Description |
|---|---|---|
label |
string |
Button label and accessible name. |
icon |
React.ComponentType |
Optional icon component. Phosphor icons recommended. |
iconOnly |
boolean |
When true and an icon is set, renders the button icon-only with the label as a tooltip. |
confirmModal |
EntityAdminBulkActionConfirmModal |
Optional confirmation dialog shown before the action runs. |
callback |
(ctx) => void | Messages | Promise<void | Messages> |
The action logic. Must call set() or map(). Return a messages object to customize toasts. |
Callback context
| Helper | Signature | Description |
|---|---|---|
set |
(data: Partial<TData>) => void |
Applies a static partial update to all selected documents. |
map |
(fields, fn) => Promise<void> |
Fetches fields for each selected document, calls fn(doc) per document, and applies the returned partial update. Use when the new value depends on current document state. |
Callback return — Messages
All keys are optional. Omitting a key falls back to a generic label-based message.
| Key | Type | Description |
|---|---|---|
success |
(count: number) => string |
Toast shown when all selected documents updated successfully. |
partialSuccess |
(succeeded: number, failed: number) => string |
Toast shown when some documents succeeded and some failed. |
error |
string |
Toast shown when all documents failed. |
EntityAdminBulkActionConfirmModal
| Property | Type | Description |
|---|---|---|
title |
string |
Modal heading. |
description |
string |
Explanatory text shown below the heading. |
actions.confirm |
string |
Confirm button label. Default: "Confirm". |
actions.cancel |
string |
Cancel button label. Default: "Cancel". |
See Admin Extensibility — Bulk actions for usage examples.
versions
Version history and the draft → publish lifecycle. Every entity and global keeps a version history by default: leaving versions out is the same as { drafts: false, limit: 50 }, so every save goes live and the last 50 versions per document can be restored from History. See the drafts guide for the full lifecycle and API surface.
// versions left out // history only, last 50 versions per document
versions: false // no history: saves overwrite, nothing is kept
versions: true // drafts + publish + history, last 50 versions per document
versions: { limit: 100 } // same, with a different per-doc cap
versions: { limit: false } // same, keeping every version
versions: { drafts: false } // history only: every save goes live and leaves a version
| Property | Type | Default | Description |
|---|---|---|---|
limit |
number | false |
50 |
Max version rows per document. Older rows are pruned automatically on every insert. Pinned rows (current pending draft and published marker) are never pruned. false keeps every version. |
drafts |
boolean |
true (false when versions is left out) |
The draft → publish workflow. false keeps the history and restore, but create, save, translate and restore put content live; draft save, discard draft and unpublish return 400. See History without drafts. |
publishedAt is always reserved and auto-injected on every entity, regardless of this setting — the schema is unified across versions on/off. With versions on, drafts have publishedAt: NULL until they’re published; with versions off, every write stamps publishedAt = now(). Toggling versions is a behavior change, never a DDL migration, except for unique rules: turning drafts on or off changes which rows their indexes cover.
With versions on, including the default, the versions.read permission gates History and its diffs, and restore and publish hooks fire as described in the drafts guide. Set versions: false on entities that write often and whose past states have no value, such as logs or counters.
unique
Values that may appear together on at most one published document per locale. Postgres enforces each rule with a partial unique index, so two editors publishing at the same moment can’t both get through.
type UniqueRule = {
fields: string[]; // top-level fields, or one key of an object: "product_ch.id"
where?: Record<string, string | boolean>; // the rule applies only to documents with these values
message?: string; // default: "Must be unique"
};
fields takes text, number, select, boolean, date and single relation fields, and the same types one level inside an object. where compares top-level select, boolean and text fields by equality. Both are typed against the entity’s fields.
// One edition per product, year and month.
entity("advent_calendar", {
translatable: true,
versions: true,
fields: [relation("product", { to: products }), number("year"), number("month")],
unique: [
{ fields: ["product", "year", "month"], message: "This product already has an edition for that month." },
],
});
// At most one blog index: no fields, only a condition.
entity("page", {
versions: true,
fields: [select("page_type", { options: ["default", "blog_index"] }), object("product_ch", { fields: [text("id")] })],
unique: [
{ fields: [], where: { page_type: "blog_index" }, message: "Another page is already the blog index." },
// One page per Shopify product. Shorthand: object("product_ch", { ..., unique: "id" }).
{ fields: ["product_ch.id"] },
],
});
| Case | Outcome |
|---|---|
| A write that would give a second published document the same values in the same locale | 400 with the rule’s message on each of its fields (on its where fields when it names none) |
| Translating a document | Allowed: the copy is in another locale |
| Two drafts with the same values | Allowed. The rule is checked when one is published |
| Unpublishing the holder, then publishing the other | Allowed |
| Two editors publishing at the same moment | One wins, the database refuses the other |
| A document with an empty value | Never collides: Postgres treats empty (NULL) values as distinct |
The scope is per locale, not per translation group: an fr-only page and a de-only page can hold the same value. An entity without drafts publishes every write, so its rules apply to every document. A field’s own unique option is shorthand for a rule on that field alone; see Fields.
Adding a rule to a table that already has rows is refused by cms migration generate like any new UNIQUE, with the query that lists the rows that would break it. Fix those rows, then generate with --accept-data-loss.
Auto-injected fields
Every entity gets: id, _type, createdAt, updatedAt, publishedAt.
Translatable entities additionally get: locale, translationGroup.
Reserved names
Always reserved: id, _type, createdAt, updatedAt, publishedAt, locale, translationGroup.
Validation
Throws on duplicate field names within the same entity.
Globals (singleton entities)
Globals are single-row entries for site-wide content: settings, navigation, footer, etc. Define them with entity() and global: true — they live in the same entities array as collection entities.
import { entity } from "@cms/config";
const siteSettings = entity("site-settings", {
global: true,
fields: [
text("siteName"),
text("siteDescription"),
relation("logo", { to: media }),
],
});
export default config({
entities: [posts, pages, siteSettings],
// ...
});
- API:
GET /api/:nameandPUT /api/:name— no ID, no list, no delete - A global has no document until its first
PUT, which creates it (beforeCreate/afterCreate, acreateaudit entry); until thenGETreturnsnull - Adding a required field to a global (or any entity) that already has rows works when existing rows can be filled:
arrayandrichTextget[], scalars get theirdefaultValue. See Adding a required field to an existing entity - Admin: appears in a “Globals” sidebar section, opens directly to the edit form (no list view)
- Permissions work the same as regular entities — note that
createanddeletepermissions have no effect for globals beforeDeleteandafterDeletehooks will never run; all other hooks work normally- Auto-injected fields:
id,createdAt,updatedAt— same as collection entities
role()
import { role } from "@cms/config";
// Admin — full access, bypasses all checks
role(name: string, { isAdmin: true }): RoleDef
// Public — unauthenticated access
role(name: string, {
public: true;
permissions: Record<string, EntityPermissions>;
signup?: {
role: string;
allow?: (email: string, context: ServerContext) => boolean | Promise<boolean>;
};
}): RoleDef
// Authenticated role
role(name: string, {
permissions: Record<string, EntityPermissions>;
adminPanel?: boolean; // default true
}): RoleDef
signup: { role } on the public role lets people without an account create one: they request a login code with signup: true and verifying it creates their user with role, which the client never chooses (see Request login code). The role must exist, can’t be an admin or public role, and must set adminPanel: false. Only the first public role is used, so signup on another one is an error.
allow decides who may sign up; without it, anyone with a valid email can. It gets the email lowercased, as it will be stored, and the server context (system, config, logger, reportError, db, email), so it can check a domain or read an invite:
role("public", {
public: true,
permissions: {},
signup: {
role: "customer",
allow: async (email, { system }) => {
const { data } = await system.list("invites", { filter: { email } });
return data.length > 0;
},
},
});
It runs before the code is sent and again before the user is created, so tightening it also stops codes already sent. A refused email gets the same 200 and no code as any unknown email, so a caller can’t probe the rule; a throw refuses too, and is logged and reported. Existing users always sign in. cms.config is also bundled into the admin, so keep server-only imports used by allow in a *.server.ts module.
adminPanel: false keeps the role’s users out of the admin: they can sign in, but see only that they have no access. Use it for the users of an app, such as customers, who reach the API under the role’s permissions but have nothing to do in the admin.
EntityPermissions
{
create?: boolean | { filter?: Record<string, unknown>; fields?: { exclude?: string[] } };
read?: boolean | { filter?: Record<string, unknown>; fields?: { exclude?: string[] } };
update?: boolean | { filter?: Record<string, unknown>; fields?: { exclude?: string[] } };
delete?: boolean | { filter?: Record<string, unknown>; fields?: { exclude?: string[] } };
}
API keys
Static tokens for headless use — static site generators, CI/CD, server-to-server calls.
GET /api/_api-keys — list all keys (prefix, name, role, last used)
POST /api/_api-keys — create key
DELETE /api/_api-keys/:id — revoke key
All endpoints require an admin session.
Create a key
POST /api/_api-keys
Content-Type: application/json
{ "name": "Blog frontend", "role": "public", "expiresAt": "2027-01-01T00:00:00Z" }
Response (201):
{
"data": {
"id": "uuid",
"name": "Blog frontend",
"keyPrefix": "cms_k_aB3xK",
"role": "public",
"key": "cms_k_aB3xK9mNpQ2rS7vW1yZ..."
}
}
The raw key is shown once on creation and cannot be retrieved again. Revoke and recreate if lost. Keys are SHA-256 hashed in the database.
expiresAt is optional. When set, expired keys are automatically rejected. Omit it for keys that don’t expire.
Using a key
GET /api/posts?filter[status]=published
Authorization: Bearer cms_k_aB3xK9mNpQ2rS7vW1yZ...
The key assumes the role it was created with. All permission rules apply normally.
Keys can also be managed from the admin UI at Settings → API Keys.
Routes
Project-defined server-side endpoints, mounted under a fixed /api/custom/:name prefix. Use this when you need a server-only secret (a third-party API key, a signing secret) that can’t live in the client-side admin SPA — for example, proxying a search call to a third-party service.
Define each one with route(). Its query and body schemas are checked before the handler runs, and the data the handler passes to routeJson() is what a typed client’s cms.route() returns.
import { config, route, routeJson } from "@cms/config";
import { z } from "zod";
export default config({
// ...
routes: [
route({
name: "reviews-search", // mounted at /api/custom/reviews-search
method: "GET", // default: "GET"
roles: ["editor"], // additive access beyond admins (see below); default: []
query: z.object({ q: z.string().min(1), limit: z.coerce.number().optional() }),
handler: async ({ query }) => {
const result = await fetch(`https://reviews.example.com/search?q=${query.q}`, {
headers: { Authorization: `Bearer ${process.env.REVIEWS_API_SECRET}` },
});
const { reviews } = (await result.json()) as { reviews: { id: string; text: string }[] };
return routeJson({ data: reviews.slice(0, query.limit ?? 10) });
},
}),
],
});
A route doesn’t need route(), schemas or routeJson(): a plain object whose handler returns any Response still works, and a typed client gets its data as unknown. Without route(), the handler’s query and body aren’t typed from the schemas.
RouteDef
| Property | Type | Description |
|---|---|---|
name |
string |
Path segment — mounted at /api/custom/:name. Must match /^[a-z0-9-]+$/. |
method |
"GET" | "POST" | "PUT" | "PATCH" | "DELETE" |
HTTP method this entry responds to. Default: "GET". |
roles |
string[] |
Role names (beyond admins, who always have access) allowed to call this route. Default: []. |
public |
boolean |
Anyone may call it, signed in or not, and roles is ignored. Default: false. |
query |
Standard Schema (e.g. a Zod schema) | Checks the query string before the handler runs. See Validation. |
body |
Standard Schema (e.g. a Zod schema) | Checks the JSON body before the handler runs. See Validation. |
handler |
(ctx: RouteContext) => Promise<Response> | Response |
Request handler. Return routeJson(data) to type the route’s data for the client, or any Response. |
RouteContext
The server context, plus the request and its caller.
| Property | Type | Description |
|---|---|---|
req |
Request |
The raw request: headers, and the query or body when there’s no schema for them. |
query |
The query schema’s output |
The parsed query string. undefined without a query schema. |
body |
The body schema’s output |
The parsed JSON body. undefined without a body schema. |
user |
{ id: string; email: string; role: string } | null |
The calling user, or null for an API key or the public role. |
role |
string |
Name of the role the caller was resolved to. |
cms |
Client |
Content calls acting as the caller: their role decides what they can do. |
Validation
query and body take any Standard Schema: a Zod schema, or a Valibot or ArkType one. The engine runs them after the access check and before the handler, which gets the parsed values as ctx.query and ctx.body.
querysees the query string parsed into an object the way entity queries are (?filter[tag]=a→{ filter: { tag: "a" } }). Every value arrives as a string, so a number needsz.coerce.number(). No query string parses to{}, neverundefined, so a default on the whole schema doesn’t apply; default its keys instead. An array holds up to 1,000 items, andtags[]reads as an empty array.bodysees the request’s JSON body, orundefinedwhen there is none, so an optional schema or one with a default accepts a call without a body. A body that isn’t JSON fails too, and one over 1 MB answers413 PAYLOAD_TOO_LARGE. The body is read from a copy, so the handler can still readreqitself.
A failure answers 400 VALIDATION_ERROR with one detail per issue, its field the path to it under query or body:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid body",
"details": [{ "field": "body.tags.1", "message": "Invalid input: expected string, received number" }]
}
}
The response isn’t validated: routeJson() types it for the client at compile time only. The client gets the data as JSON delivers it, so a Date types as a string, and a key that is undefined as optional.
Server-only code
The config, handlers included, is also bundled into the admin SPA. Keep Node-only imports (SDKs,
database drivers, secrets) in a *.server.ts file: the engine runs it, and the admin build swaps it
for a stub whose exports throw if called in the browser. Keep the route() call and its schemas in
the config, and only the handler’s body in the .server.ts file.
// lib/reviews.server.ts
import { routeJson, type RouteContext } from "@cms/config";
import { ReviewsClient } from "reviews-sdk";
const reviews = new ReviewsClient({ secret: process.env.REVIEWS_API_SECRET! });
export async function searchReviews({ query }: RouteContext<{ q: string }>) {
return routeJson({ data: await reviews.search(query.q) });
}
// cms.config.tsx
import { searchReviews } from "./lib/reviews.server";
export default config({
// ...
routes: [
route({ name: "reviews-search", query: z.object({ q: z.string() }), handler: searchReviews }),
],
});
See Hooks → Server-only code for the full rules.
Access control
A route is reachable by any role with isAdmin: true, plus any role listed in roles. There’s no way to lock a route out entirely — admins always have access.
public: true opens a route to everyone: callers with no credentials, whether or not the project defines a public role, and every role. Use it for answers that are public anyway, like a lookup a website makes on each request. Credentials that are sent must still be valid, so a bad API key gets 401 even on a public route.
Responses and errors
routeJson(data, init?) answers data as JSON, status 200 unless init sets another (routeJson(data, { status: 201 })). It is Response.json() with the data’s type attached, which is how cms.route() knows what a route returns.
Use routeError(status, code, message) to return the CMS’s standard { error: { code, message } } JSON shape for expected errors (upstream 4xxs, a missing record). cms.route() throws it as a ClientError. Unhandled exceptions thrown from handler are caught by the engine’s global error handler and return a generic 500.
Typed calls from a client
A client typed with the project’s config calls a route by its path, with query, body and the result typed from the route. A wrong path, method or input is a type error:
const cms = createClient<typeof cmsConfig>({ url });
const { data } = await cms.route("/custom/reviews-search", { query: { q: "cheese" } });
Routes keep their types only when they’re written inside config({ routes: [...] }). A list declared beforehand as RouteDef[] still works, with any /custom/... path accepted and unknown results. See cms.route().
Not included
Routes don’t appear in the @cms/openapi spec and aren’t surfaced in the admin UI. A route has one name per method: there are no path parameters (/custom/items/:id); pass an id in the query or body.
Server context
What hooks, routes, plugin observers and a plugin’s server.ready receive. cms and system are
@cms/client instances that run in-process through the REST code path, so
permissions, validation, versions, translations, hooks and relation resolution all apply. A failed
call throws ClientError (from @cms/config) with status, code and details; check for it
with isClientError(error), since instanceof fails across the config’s own module copy.
| Property | Type | Description |
|---|---|---|
system |
Client |
Full access. On an entity with drafts (versions: true), reads return published documents only, unless the call passes draft: true for the editorial view (pending drafts merged, unpublished included). An entity without drafts (the default) has no unpublished state, so every document is read. |
config |
CmsConfig |
The resolved config, plugin entities included. Read-only. |
logger |
{ info, warn, error } |
The engine’s logger, tagged with the plugin, entity or route. |
reportError |
(error: unknown) => void |
Hands a failure to every plugin’s server.onError. |
db |
unknown |
Unstable. The raw Drizzle database. Its tables are the storage layout, which can change in any release, and queries through it skip permissions, validation, versions and hooks. |
email |
{ send(message) } |
Sends an email through the configured provider (printed to the console without one). See ctx.email. |
Where there’s a caller, the context also has cms, acting as that caller, with their user and
role:
| Context | cms |
system |
Also |
|---|---|---|---|
RouteContext |
the caller | yes | req, user, role |
HookContext |
the caller | yes | entityName, user, role (after-hooks) |
BeforeHookContext |
find, list, get |
find, list, get |
entityName, user, role. Reads run on the write’s transaction. |
ObserverContext |
— | yes | entityName, and the user and role that made the write |
server.ready |
— | yes | mode |
RootRouteContext |
— | yes | req and config only |
See Hooks → Hook context for when to use cms or system, and why
before-hooks can only read.
ctx.email
ctx.email.send(message) sends through the email provider, the same path the login
code takes. The Emails guide has worked examples. Without a provider it prints the recipient, subject and text part to the console.
import { html } from "@cms/config";
afterCreate: async (order, ctx) => {
await ctx.email.send({
to: order.email,
subject: `Order ${order.number}`,
html: html`<p>Thanks, ${order.name}.</p>`,
text: `Thanks, ${order.name}.`,
replyTo: "help@acme.com",
});
},
| Field | Type | Description |
|---|---|---|
to |
string |
One recipient: an address, no list. |
subject |
string |
No line breaks. |
html |
string | SafeHtml |
The body. The html tag escapes what it interpolates; a plain string (from a renderer) is sent as is. |
text |
string |
Optional plain-text part. Some clients and spam filters prefer it. |
from |
string |
Optional. Overrides the provider’s from: one address or Name <address>, the name sent quoted. SES needs it verified. |
replyTo |
string |
Optional. One address or Name <address>, the name sent quoted. |
send rejects when the message is invalid (a ValidationError naming the field, a 400 if it
escapes a route; nothing reaches the provider) or delivery fails, so the caller decides whether
that fails what it’s doing. It runs inline, with no queue or retries. After-hooks run after the
commit, so awaiting a send there holds nothing back. A send from a before-hook goes out even when
the write then fails: send from the after-hook when the email depends on the write.
Plugins
Optional features are plugins, registered in one array. Each entry is an instance, named after its
plugin unless you pass name; two instances with the same name throw. See
Plugins for what a plugin can do and how to write one.
A plugin’s entities are added to yours, its routes mount at
/api/plugins/<instance-name>/<route>, and its root paths (such as /openapi.json) at the exact
path it names. Its admin pages mount at /admin/plugins/<instance-name>/<path>. See
Plugins → Contributions.
import { sentry } from "@cms/sentry";
plugins: [sentry({ dsn: process.env.SENTRY_DSN })],
The CMS ships three plugins: Sentry and OpenAPI below, and Redirects, which has its own guide.
definePlugin()
definePlugin(name: string, create: (options, instance: { name: string }) => PluginDefinition)
Returns the factory a project calls in plugins. name (/^[a-z0-9-]+$/) is the default
instance name; every factory also accepts name in its options to override it. create runs
wherever cms.config is evaluated, in Node and in the admin, so it only builds the definition.
Unstable until 1.0. See Plugins → Writing a plugin.
Every key of the definition is optional:
| Key | Runs | Receives | A throw |
|---|---|---|---|
entities |
— | — | — |
routes |
Server, per request to /api/plugins/<instance>/<route> |
RouteContext |
Answers 500, reported to onError |
root |
Server, per GET of its exact path, before auth |
{ req, config, system } |
Answers 500, reported to onError |
observers.match |
Server, once per entity at boot | the entity | Fails the boot |
observers.afterCreate / afterUpdate / afterPublish / afterUnpublish |
Server, after each committed write to a matched entity | (document, ObserverContext) |
Logged and reported; the write stands |
observers.afterDelete |
Same | (id, ObserverContext) |
Same |
server.setup |
Server, once at boot, before the database connects | { mode, logger } |
Fails the boot |
server.ready |
Server, once at boot, after the app is built, before it listens | Server context + mode |
Fails the boot |
server.onError |
Server, per reported failure | (error, { source, requestId?, method?, path?, userId?, role?, entity?, hook?, plugin? }) |
Logged and skipped |
server.onLog |
Server, per warn or error log line |
{ level, message, attributes } |
Logged and skipped |
server.flush |
Server, on shutdown and before a crash exit | timeoutMs |
Logged and skipped |
admin.routes |
Admin, when the page is opened | — | Render error |
admin.setup |
Admin, once at boot | { data }: what server.setup returned as admin |
The plugin’s other admin hooks are skipped |
admin.onError |
Admin, per render error or failed query or mutation (not 4xx) | (error, { source, requestId? }) |
Swallowed; the admin carries on |
admin.onUser |
Admin, on sign-in and logout | { id, role } or null |
Swallowed; the admin carries on |
build.vite |
cms build only |
— | Fails the build |
server.setupreturns{ admin?: JsonValue };adminis served publicly in/admin/runtime-env.js.build.vitereturns{ plugins?: VitePlugin[], sourcemap?: "hidden" }.entities,routes,rootandadmin.routestake the same shapes as the project’s own entities, routes and admin routes. Routes and pages mount under the instance name; root paths are exact paths outside/api,/adminand/healthz.
config() throws when a plugin’s entity name, route, root path or instance name collides with
another source, or when its routes or pages name a role the project doesn’t define.
Sentry (@cms/sentry)
Error monitoring for the engine and the admin. See Deployment → Error monitoring for what gets reported.
sentry({
dsn: process.env.SENTRY_DSN, // unset → Sentry stays off
environment: process.env.APP_ENV, // e.g. "staging" / "production"
release: process.env.APP_VERSION,
sourceMaps: { // admin source-map upload during `cms build`,
org: "my-org", // when SENTRY_AUTH_TOKEN is set at build time
project: "my-project",
},
})
| Option | Type | Description |
|---|---|---|
dsn |
string |
Where events go. Leave unset to keep Sentry off. |
environment |
string |
Sentry environment. |
release |
string |
Release name, usually the deployed version. |
sourceMaps.org |
string |
Sentry organization slug — only for the admin source-map upload. |
sourceMaps.project |
string |
Sentry project slug — only for the admin source-map upload. |
name |
string |
Instance name. Default: "sentry". |
OpenAPI (@cms/openapi)
Serves an OpenAPI 3.1 spec of the REST API at /openapi.json and an interactive Scalar API
reference at /docs, both public. See REST API → API reference.
import { openapi } from "@cms/openapi";
plugins: [openapi()],
It takes no options. Registering it twice throws, since both instances would claim the same paths.
AdminConfig
{
logo?: string;
title?: string;
sidebar?: (builders: SidebarBuilders, context: { user: CmsUser }) => SidebarElement[];
dashboard?: React.ComponentType;
routes?: AdminRouteDef[];
}
routes
Pages rendered inside the admin shell at /admin/custom/<path>, each with a sidebar item.
routes: [
{
path: "reports", // lowercase segments: "reports", "reports/monthly"
label: "Reports", // sidebar label
icon: ChartBarIcon, // optional
roles: ["editor"], // beyond admins, who always have access; default: []
component: () => import("./admin/reports"),
},
],
| Field | Type | Description |
|---|---|---|
path |
string |
One or more segments matching /^[a-z0-9-]+$/, joined by /. Unique. |
label |
string |
Sidebar label. |
icon |
React.ComponentType |
Sidebar icon. |
roles |
string[] |
Role names (beyond admins) allowed to open the page. Others get a “not found” page. Default: []. |
component |
() => Promise<{ default: React.ComponentType }> |
Always a () => import(): the page loads only when opened, and never in Node. |
The role check hides the page in the admin; protect the data it reads with entity permissions or a
server route’s roles. See Admin Extensibility — Pages.
sidebar
A function that receives builder helpers and the signed-in user, and returns an array of sidebar elements. The admin calls it for each user, so the layout can depend on who is signed in. When omitted, the default sidebar is generated automatically: Dashboard, your pages, your entities, your globals, a Plugins group with one element per plugin, then Assets. A custom sidebar gets no plugin items injected, and cms dev warns about plugin pages and entities it leaves out.
sidebar: ({ group, item, page, plugin, plugins, divider, builtins }, { user }) => SidebarElement[]
user is a CmsUser: { id, email, name, role }. The second argument is optional: a
(builders) => [...] function works as is. The sidebar is layout only, not access control: an
item left out can still be opened by URL and through the API. Access is set through role
permissions, and non-admin roles also get the result filtered by them.
Builders
| Builder | Returns | Description |
|---|---|---|
item(name, options?) |
SidebarItem |
Link to an entity or global. Name is auto-resolved. Options: { label?, icon? } |
group(label, options) |
SidebarGroup |
Labeled section. Options: { icon?, collapsible?, defaultOpen?, indent?, children } |
page(path, options?) |
SidebarPage |
Link to one of your admin.routes pages, or a plugin’s with plugin. Options: { plugin?, label?, icon? } |
plugin(name) |
SidebarGroup | SidebarPage | SidebarItem |
A plugin instance’s group: its pages, then its entities. A plugin that is one page or one entity gives that item alone |
plugins({ except? }) |
(SidebarGroup | SidebarPage | SidebarItem)[] |
One element per plugin with pages or entities, in registration order |
divider() |
SidebarDivider |
Horizontal separator |
builtins.DASHBOARD |
SidebarItem |
Built-in dashboard item |
builtins.ASSETS |
SidebarItem |
Built-in assets manager item |
Groups accept any SidebarElement[] as children, so they can be nested.
See Admin Extensibility — Sidebar for usage examples.
Previous
Field types
Next
CLI