Fields
Define your content model with typed field helpers.
Fields are the building blocks of entities. Each field helper is a plain factory function that returns a typed field definition. The system infers storage strategy from the field type — you never decide whether something is a column or JSONB.
Field types
text
String values. Maps to a Postgres text column.
import { text } from "@cms/config";
text("title", { required: true });
text("bio");
text("email", { unique: true, required: true });
slug
A shorthand for text fields with slug semantics. Globally unique — enforced by the _slug table’s primary key rather than a per-column constraint.
import { slug } from "@cms/config";
slug("slug", { required: true });
Slugs can encode path hierarchy: /blog/2025/my-post. See Querying for glob-based filtering.
With source, a write that leaves the slug empty derives it from another field (or from a function of the document):
slug("slug", { source: "title" });
A write that doesn’t send the slug keeps a hand-set one. A slug still equal to what its source derives follows the source, so renaming the title moves it. Sending null or "" derives it again.
number
Numeric values. Maps to a Postgres double precision column.
import { number } from "@cms/config";
number("price");
number("sortOrder", { required: true });
boolean
Boolean values. Maps to a Postgres boolean column.
import { boolean } from "@cms/config";
boolean("featured");
boolean("active", { defaultValue: true });
date
Timestamp values. Maps to Postgres timestamptz. Values are ISO 8601 strings.
import { date } from "@cms/config";
date("scheduledFor");
select
Constrained text values from a fixed set of options. Maps to a text column. Options are type-safe via const assertion.
import { select } from "@cms/config";
select("status", { options: ["draft", "published", "archived"] });
select("priority", { options: ["low", "medium", "high"], required: true });
For human-friendly labels distinct from the stored value, pass { label, value } objects instead of plain strings. The database stores value; the admin UI shows label. Mix both forms freely in the same list.
select("region", {
options: [
{ label: "North America", value: "na" },
{ label: "Europe", value: "eu" },
{ label: "Asia Pacific", value: "apac" },
],
});
json
Arbitrary JSON. Maps to a Postgres jsonb column. Use when you need unstructured data.
import { json } from "@cms/config";
json("metadata");
For structured nested data, prefer object instead.
richText
Rich text content stored as Portable Text JSON. The admin provides a WYSIWYG editor.
import { richText } from "@cms/config";
richText("body");
richText("excerpt", { required: true });
- Storage:
jsonb - API value: Array of Portable Text blocks
- Required:
required: truerejects an empty array - Admin: Toolbar-based rich text editor
- Frontend rendering: Use
@portabletext/reactor any Portable Text renderer
Customizing the editor
The richText field is fully configurable. You can control which styles, decorators, lists, annotations, blocks, and inline blocks are available.
Styles control block-level formatting (headings, blockquote, etc.). Decorators control inline formatting (bold, italic, etc.). Lists control list types. Pass plain strings to use built-in defaults.
richText("body", {
styles: ["h1", "h2", "blockquote"],
decorators: ["bold", "italic", "code"],
lists: ["bullet", "number"],
});
Annotations
Annotations are inline marks with structured data — like links with a URL, or footnotes with content. Each annotation has a name and a set of fields that the user fills in via a popover when the annotation is applied.
richText("body", {
annotations: [
richText.annotation("link", {
fields: [
text("url", { required: true }),
],
}),
richText.annotation("footnote", {
fields: [
text("note", { required: true }),
],
}),
],
});
Annotation data is stored in the block’s markDefs array:
{
"_type": "block",
"markDefs": [
{ "_type": "link", "_key": "abc", "url": "https://example.com" }
],
"children": [{ "_type": "span", "text": "click here", "marks": ["abc"] }]
}
Blocks
Blocks are structured objects that live between text blocks — images, embeds, CTAs, etc. Each block has a name and fields.
richText("body", {
blocks: [
richText.block("image", {
fields: [text("url", { required: true }), text("alt")],
}),
richText.block("callout", {
fields: [
select("tone", { options: ["info", "warning", "error"] }),
text("message", { required: true }),
],
}),
],
});
Block data in the API includes a _type discriminator:
{ "_type": "image", "_key": "xyz", "url": "/photo.jpg", "alt": "A photo" }
Inline blocks
Inline blocks are like blocks but rendered inline within text — think inline images, status badges, or mentions. Same API as blocks, created with richText.inlineBlock.
richText("body", {
inlineBlocks: [
richText.inlineBlock("inline-image", {
fields: [text("url", { required: true })],
}),
],
});
Tables
Set table: true to enable the built-in table block. Cells hold regular rich text, so the styles, decorators, annotations, and inline blocks configured on the field work inside them.
richText("body", { table: true });
A table is stored as a table block whose rows hold cells, each with a value array of Portable Text blocks. headerRows counts the leading rows rendered as headers.
{
"_type": "table",
"_key": "xyz",
"headerRows": 1,
"rows": [{ "_key": "r1", "cells": [{ "_key": "c1", "value": [] }] }]
}
Full example
richText("body", {
styles: ["h1", "h2", "h3", "blockquote"],
decorators: ["bold", "italic", "underline", "code"],
lists: ["bullet", "number"],
annotations: [
richText.annotation("link", {
fields: [text("url", { required: true })],
}),
],
blocks: [
richText.block("image", {
fields: [text("url", { required: true }), text("alt")],
}),
],
inlineBlocks: [
richText.inlineBlock("mention", {
fields: [text("name", { required: true })],
}),
],
});
relation
Links to other entities. See the Relations guide for details.
import { relation } from "@cms/config";
relation("author", { to: authors });
relation("tags", { to: tags, multiple: true });
relation("link", { to: [pages, posts] }); // polymorphic
Handling multiple relations
To reference multiple items from another entity, use multiple: true on the relation. array() wrapping a relation is rejected at config build:
// Correct — junction table, referential integrity, filtering, resolution, ordering
relation("tags", { to: tags, multiple: true, min: 1, max: 5 });
// Rejected at config build
array("tags", { of: relation("value", { to: tags }) });
// ^ throws: "array(...) cannot contain a relation. Use relation(..., { multiple: true })"
There is one canonical way to express many-relations in the DSL — relation({ multiple: true }). It backs the relation with a junction table (referential integrity, filtering, resolution, and ordering), and supports min/max for length validation.
image, video, file
Typed shorthands for relations to the three built-in asset entities. Use these for file uploads.
import { image, video, file } from "@cms/config";
image("featuredImage");
image("gallery", { multiple: true });
video("demoVideo");
file("attachment", { required: true });
file("downloads", { multiple: true });
Each helper creates a relation to its corresponding built-in entity (_image, _video, _file). In the admin UI, they render typed upload inputs with preview, browse, and remove controls instead of the generic relation picker.
For fields that accept multiple asset types, use relation() with a polymorphic target:
relation("media", { to: ["_image", "_video"] })
See the Assets guide for upload handling, MIME routing, image transforms, and querying.
object
Structured nested data stored as JSONB. Contains its own fields.
import { object, text, number } from "@cms/config";
object("seo", {
fields: [text("title"), text("description"), text("ogImage")],
});
Objects can be nested and used as block definitions.
When an object is used inside an array() or union(), the admin shows each collapsed row’s title (falling back to name) as its disclosure title. Set admin.summary.title to a field to show its live value instead — handy for telling apart otherwise-identical rows at a glance:
array("faqs", {
of: object("faq", {
fields: [text("question", { required: true }), richText("answer")],
admin: { summary: { title: "question" } },
}),
});
The field can also be a dotted path into an object field, for rows whose meaningful value is nested:
array("addons", {
of: object("addon", {
fields: [object("product", { fields: [text("title"), text("handle")] })],
admin: { summary: { title: "product.title" } },
}),
});
The path is type-checked against the nested fields, up to three object levels deep, so a misspelled segment is a type error. It’s read segment by segment from the row’s data. A select shows its option’s label, not the stored value. If the path doesn’t end on a non-empty string, a number or a boolean, the row falls back to title, then name.
When the path names a single relation (directly or at the end of a dotted path), the row shows the related document’s admin.summary.title, so rows that only hold a reference can still be told apart:
array("blocks", {
of: object("synced", {
fields: [relation("block", { to: "synced_block" })],
admin: { summary: { title: "block" } },
}),
});
The admin loads the related documents for all rows in one request per entity. Until they load, or if the related document is gone, the row shows title, then name. This applies to array() rows. Rich-text blocks take a field name or dotted path but don’t resolve relations.
For a row one field can’t describe, title takes a function of the row’s data, and media renders before it:
object("band", {
fields: [text("name"), select("theme", { options: THEMES })],
admin: {
summary: {
title: ({ data }) => data.name ?? "Band",
media: ({ data }) => <Swatch colour={SURFACE_HEX[data.theme ?? "bark"]} />,
},
},
});
data is typed from fields, with every value optional: a row just added has none yet. When the function renders nothing, the row falls back to the object’s title, then name.
In an array of a union(), a row named by its own value starts with its variant’s title, muted: FAQ · Why choose us?. A union()’s admin.icons (keyed by variant name) adds an icon before it; blocks() sets it from each variant’s icon. An object’s media takes the icon’s place.
previewField: "question" is the deprecated spelling of admin: { summary: { title: "question" } } and still works.
union
A single polymorphic object — one of several object shapes, discriminated by a _type key. Use this when a field holds exactly one typed value and you need to know which shape it is.
import { union, object, text, number } from "@cms/config";
const imageHero = object("image_hero", {
fields: [text("src", { required: true }), text("alt")],
});
const videoHero = object("video_hero", {
fields: [text("url", { required: true }), number("duration")],
});
union("hero", { of: [imageHero, videoHero] });
In the API response, the value includes a _type discriminator:
{ "_type": "image_hero", "src": "/photo.jpg", "alt": "A photo" }
- Storage:
jsonb - API value: A single object with
_typeset to the variant name - Admin: A type selector followed by the selected variant’s fields
array
Repeating values stored as JSONB. Use a primitive field for flat arrays, or an object field for arrays of objects.
import { array, object, relation, text } from "@cms/config";
// Array of strings
array("tags", { of: text("value") });
// Array of objects
array("gallery", {
of: object("item", {
fields: [relation("image", { to: media }), text("caption"), text("alt")],
}),
});
- Storage:
jsonb - API value: Array of primitives or array of objects, depending on
of - Admin: Add/remove/reorder items with up/down buttons
Blocks pattern
To model a list of polymorphic sections (the “page builder” pattern), combine array with union:
import { array, union, object, text, relation } from "@cms/config";
const hero = object("hero", {
fields: [text("heading", { required: true }), text("subheading")],
});
const callout = object("callout", {
fields: [text("message", { required: true })],
});
const imageBlock = object("image_block", {
fields: [relation("image", { to: media }), text("caption")],
});
array("sections", {
of: union("section", { of: [hero, callout, imageBlock] }),
});
Each item in the array is a union value, so every element carries a _type discriminator:
[
{ "_type": "hero", "heading": "Welcome" },
{ "_type": "callout", "message": "Sign up today" },
{ "_type": "image_block", "caption": "Our team" }
]
The “Add item” button opens a dropdown of the variants. For a page builder with many blocks, blocks() from @cms/blocks replaces union() with a two-pane picker: a searchable list of blocks and the presets editors can start from (a block with presets inserts its first one, with “Empty” for a blank block), beside a preview of the highlighted one (live on your website’s canvas, or its static thumbnail). See Block picker.
import { blocks } from "@cms/blocks";
import { ImageIcon, MegaphoneIcon } from "@phosphor-icons/react";
import heroThumbnail from "./thumbnails/hero.png";
array("sections", {
of: blocks("section", {
of: [hero, callout, imageBlock],
variants: {
hero: {
thumbnail: heroThumbnail, // the preview without a canvas; falls back to `icon`
icon: ImageIcon,
presets: [
{
label: "Launch",
value: { heading: "Something new", subheading: "Out today" },
locales: { pt: { label: "Lançamento", value: { heading: "Algo novo" } } },
},
],
},
callout: { icon: MegaphoneIcon },
},
}),
});
variantsis keyed by each block’s name; a key that isn’t inofis a type error.- A variant’s
icon(or the puzzle piece when it has none) also starts each of its rows in the array. - A preset’s
valuemay leave out any field, and relations are never checked.blocks()throws if a value doesn’t fit its block’s fields. - Order presets with the one editors reach for most first: the picker inserts it when the block is chosen, and the block playground opens on it.
localesoverrideslabelandvaluefor documents in that locale. Type the presets asBlockPreset<typeof hero, Locale>[]to check the locale keys.blocks()returns a plainunion()field: stored data, migrations and client types are the same.- A variant’s
grouplists it under a heading, and acanvas(withblocksPlugin()’s block playground) renders blocks with your website. See Blocks.
Layout directives
Layout directives are pure admin UI — no storage, no columns. Mix them into the fields array alongside regular fields.
import { tabs, collapsible, row } from "@cms/config";
entity("pages", {
fields: [
text("title", { required: true }),
slug("slug"),
tabs([
{
label: "Content",
fields: [union("hero", { of: [imageHero, videoHero] })],
},
{
label: "SEO",
fields: [
object("seo", { fields: [text("title"), text("description")] }),
],
},
]),
collapsible("Advanced", [boolean("featured"), date("scheduledFor")]),
row([
select("status", { options: ["draft", "published"] }),
date("scheduledFor"),
]),
],
});
tabs(tabDefs)— tabbed sections. Each tab haslabel,fields, and an optionalvisible.collapsible(label, fields, { defaultOpen? })— collapsible section, closed by default.row(fields)— renders fields side by side.
Directives can be nested. They have no storage impact — invisible to migrations and the API.
Conditional tabs
A tab can be hidden entirely with visible — unlike a field’s admin.visible (which only suppresses the input while keeping its last submitted value), an invisible tab has no representation in the tab strip or panels at all. Use it when every field in a tab shares one gating condition, so editors never land on a tab that’s empty for the current row:
select("page_type", { options: ["blocks", "group"], required: true }),
tabs([
{
label: "Content",
fields: [array("blocks", { of: union("block", { of: [hero, faq] }) })],
},
{
label: "Group",
fields: [text("subtitle"), array("groups", { of: collectionRail })],
visible: ({ data }) => data.page_type === "group",
},
]),
Same { data, user } context as admin.visible (minus value, since a tab isn’t a single field). Fails open while the current user hasn’t loaded yet.
Common options
All field types share these base options:
{
title?: string; // human-readable label shown in the admin UI instead of the field name
description?: string; // helper text rendered below the label in the admin UI
required?: boolean | ((ctx: { data }) => boolean); // default: false
defaultValue?: TValue; // initial form value in the admin; on the server, fills a required field a create leaves out
validate?: (value: TValue, ctx: { data }) => true | string; // runs on the server and in the admin
admin?: {
components?: FieldSlotComponents; // custom admin UI component overrides (root, label, input, error)
visible?: (ctx: AdminFieldCtx) => boolean; // conditionally hide the field in the admin form
readOnly?: (ctx: AdminFieldCtx) => boolean; // conditionally disable the input
};
}
Unique values
text, number, select, date and single relation accept unique: true: no two published documents of the entity may hold the same value in the same locale. An object takes the name of one of its fields instead, to make that value unique:
text("sku", { unique: true }); // = entity rule { fields: ["sku"] }
object("product_ch", { // = entity rule { fields: ["product_ch.id"] }
fields: [text("id"), text("handle")],
unique: "id",
});
Each is shorthand for an entity unique rule on that field alone. Use the rule itself for several fields together, a condition or your own message:
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." },
],
});
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." },
{ fields: ["product_ch.id"] },
],
});
A write that breaks a rule fails with 400, the rule’s message (default “Must be unique”) on each of its fields, and the admin shows it on those inputs. Drafts never collide: the check runs when a document is published. A translation is in another locale, so translating a document with a unique value succeeds.
Rules that read the document
required and validate can look at the rest of the document. Both get { data }, the whole document, also for a field nested in an object, array or union.
A page of type “group” needs at least one collection rail; other pages don’t:
select("page_type", { options: ["blocks", "group"], required: true }),
array("groups", {
of: collectionRail,
required: ({ data }) => data.page_type === "group",
admin: { visible: ({ data }) => data.page_type === "group" },
}),
A date range whose end must come after its start:
date("from"),
date("to", {
validate: (value, { data }) => !data.from || value > String(data.from) || "“To” must be after “From”",
}),
| Server | Admin | |
|---|---|---|
required: true |
Always required. NOT NULL column, non-optional client type. |
Asterisk always. |
required: ({ data }) => boolean |
Checked on create, draft save, publish, bulk update and version restore, against the merged document (submitted data over the stored one). The column is nullable and the client type optional. | Asterisk follows the form as you type. |
validate(value, { data }) |
Runs on the same writes and document, only when the value is present. | Same function. |
- A failing rule returns a field-level error,
{ field: "groups", message: "Required" }. Nested fields use the dotted path, such asitems.1.url. - An empty string or an empty array counts as missing.
- The admin checks the rules when you save. After that, errors appear and clear as you edit.
datanever includes the user, so the same function gives the same answer on the server and in the admin. Rules that depend on who is writing, or that query other documents, belong in an entity hook.- A field hidden by
admin.visibleis still checked. Visibility is a display concern; give hidden fields a predicate that matches the visibility condition, as above. - Translating a document copies it without checking rules, the same as other validation.
- Changing
required: trueto a function generates a migration that dropsNOT NULL. - One-argument validators keep working.
Field visibility and access
Three separate concerns, three separate mechanisms — there is no single “hidden” flag:
| Concern | Mechanism |
|---|---|
| React to form state (sibling fields) — show “scheduledFor” only when “status” is “scheduled” | admin.visible(ctx) / admin.readOnly(ctx) |
| React to the current user (role, identity) — hide internal notes from non-editors | admin.visible(ctx) / admin.readOnly(ctx) |
| Block at the API boundary — strip fields from requests and responses for a role | permission.fields.exclude |
| Server-owned values — compute deterministically in a hook | beforeCreate / beforeUpdate hook + exclude from writeable roles |
admin.visible and admin.readOnly are admin UI only — they do not affect the API. For server-side enforcement, layer them with permissions.
Conditional visibility — admin.visible(ctx)
A function on any field that returns false to hide it. Re-runs on every form change, so visibility tracks the live unsaved row.
admin.visible: (ctx: { value: unknown; data: Record<string, unknown>; user: CmsUser }) => boolean
datais the full unsaved entity row — every sibling field is readable here, including ones that are themselves hidden. Hiding does not strip the value; it only suppresses the input. On save, the hidden field’s last value is submitted to the API.useris the authenticated admin user, including their role.valueis the unsaved value of this field — reach for it only when the condition depends on the field’s own contents.
Show a field based on a sibling value:
boolean("shippingRequired"),
object("shippingAddress", {
fields: [text("street"), text("city"), text("postalCode")],
admin: {
visible: ({ data }) => data.shippingRequired === true,
},
}),
Show a field based on the current user’s role:
text("internalNote", {
admin: {
visible: ({ user }) => user.role === "editor",
},
}),
Combine both — a “scheduledFor” date only visible when status is “scheduled”:
select("status", { options: ["draft", "scheduled", "published"] }),
date("scheduledFor", {
admin: {
visible: ({ data }) => data.status === "scheduled",
},
}),
Hidden fields are not stripped from the payload. If you need the value to actually be discarded — or the field to be unreadable across the API — pair admin.visible with permission.fields.exclude on the relevant role. See Permissions.
Works inside any layout directive (tabs, collapsible, row).
Conditional disable — admin.readOnly(ctx)
Same { value, data, user } signature. Renders the field but disables the input — useful for fields the current user can read but not edit:
text("approvedBy", {
admin: {
readOnly: ({ user }) => user.role !== "admin",
},
}),
Typing the value argument
value is typed as unknown, not the field’s runtime type. When these callbacks run in the form renderer, TypeScript can’t carry the field-specific narrowing into the function arguments (a known limitation when iterating over a discriminated union of fields). Narrow inside the function body:
text("excerpt", {
admin: {
visible: ({ value }) => {
if (typeof value !== "string") return true; // show when empty/null
return value.length > 0;
},
},
}),
For most uses you only need data and user — and those carry precise types. The value argument is the unsaved value of this field; reach for it only when the condition depends on its current contents.
visibleandreadOnlyrun in the admin SPA (the config is bundled into it at build time). The functions execute as-is — no serialization, closures over module-level imports are fine.
Custom field components
Every field supports per-slot component overrides via admin.components. You can override any combination of five slots: root, label, description, input, and error. Each custom component receives a Default prop — the built-in component for that slot — so you can wrap or extend the default rendering without replacing it entirely.
Custom components are styled with the admin’s Tailwind theme, not your website’s; see Styling custom components.
import type { InputSlotProps, LabelSlotProps } from "@cms/config";
text("title", {
admin: {
components: {
// Wrap the default input with a character counter
input: ({ Default, value, ...props }: InputSlotProps) => (
<div>
<Default value={value} {...props} />
<span>{(value as string)?.length ?? 0} / 100</span>
</div>
),
// Add a badge next to the default label
label: ({ Default, ...props }: LabelSlotProps) => (
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
<Default {...props} />
<span>AI</span>
</div>
),
},
},
});
Slot reference
| Slot | Props | Purpose |
|---|---|---|
root |
Default, field, label, description, input, error |
Wraps the entire field |
label |
Default, field, htmlFor |
The field label |
description |
Default, field |
Helper text below the label |
input |
Default, field, value, onChange, id, disabled, invalid, errors |
The input control |
error |
Default, error, id |
The validation error message |
Each slot is optional. Omitted slots use the built-in default. To fully replace a slot, ignore Default and render your own JSX. To extend it, render <Default {...props} /> and add your customizations around it.
A union() has one more slot, picker (PickerSlotProps), which replaces the dropdown that picks a variant, both for the union’s own “Add” button and, in an array of that union, for “Add item” and the + between rows. It receives Default, field, onAdd, disabled, asChild and the button as children. Call onAdd({ _type, ...values }) to add an item, prefilled with any other keys. In an array it also receives position: { index, total, host } (PickerPosition): the index the item goes in at (total appends), the number of rows, and the array field that holds the union, plus after and before, the labels of the rows on either side as the rows show them (none before the first row or after the last), to tell the editor where the item goes; a union field of its own gets no position. blocks() from @cms/blocks is built on it.
Custom fields as wrapper functions
Custom fields are just wrapper functions. No registry, no special API:
const colorPicker = (name: string, opts?: TextOptions) =>
text(name, {
validate: (v) => /^#[0-9a-f]{6}$/i.test(v),
admin: {
components: {
input: ({ Default, ...props }) => <ColorPickerInput {...props} />,
},
},
...opts,
});
// Usage — same as any built-in field
const brand = entity("brand", {
fields: [
text("name", { required: true }),
colorPicker("primaryColor"),
colorPicker("secondaryColor"),
],
});
The migration system sees the base type (text → text, json → jsonb). The admin sees the component override.
Storage strategy
Storage is automatic, inferred from the field type:
| Field type | Storage | Postgres |
|---|---|---|
text, slug, select |
Column | text |
number |
Column | double precision |
boolean |
Column | boolean |
date |
Column | timestamptz |
json |
JSONB | jsonb |
object, union, array, richText |
JSONB | jsonb |
relation (single) |
Column | FK (uuid REFERENCES ...) |
relation (multiple) |
Junction table | Separate table with <entity>_id, <target>_id (target_id for a self-relation), position |
Previous
Configuration
Next
Relations