CMS Plugin
Headless CMS with code-defined content types, dynamic forms, and agency-friendly workflows
Best for
Teams that want developers to own content models while editors manage records through an in-app admin interface.
Define structured content in TypeScript and give operators generated forms for managing it.

BTST supplies
- Content-type and content-item data models with typed CRUD APIs and lifecycle hooks
- Admin routes for content-type lists, entries, creation, and editing
- Schema-driven forms generated from adopter-defined Zod content types
- Client hooks plus customizable and ejectable admin pages
You supply
- Code-defined Zod content types and application-owned public rendering
- A BTST database adapter
- An image upload implementation when file fields are enabled
- Authorization rules when content operations are protected
You own and customize
Content models live in your code and records stay in your database. You own public rendering and uploads; the packaged admin pages can be overridden or ejected.
Compatibility and dependencies
Maintained: Next.js 15+ App Router, React Router v7, TanStack Start.
Requires: A BTST database adapter; Code-defined Zod content types.
External services: None required.
From registration to result
A semantic workflow, not a setup shortcut
- 1Model
Define each content type as a shared Zod schema in your app.
- 2Generate forms
Turn schema fields and metadata into validated operator-facing forms.
- 3Manage
Create and edit typed content records through the admin routes.
- 4Render
Load records with packaged hooks and present them on application-owned routes.
Install CMS separately alongside core v6:
pnpm add @btst/stack@6.2.0 @btst/plugin-cms@1.2.0The CMS schema includes a (contentTypeId, createdAt) baseline index for content
type paging. Regenerate the schema and apply an ORM migration to add it to an
existing database. This index does not accelerate JavaScript matching of JSON
fields; application-specific search fields and indexes remain explicit.
Installation
Ensure you followed the general framework installation guide first.
1. Define Content Types
Create your content types as Zod schemas in a shared file. This allows you to use the schemas on both server (for validation) and client (for type-safe hooks). Use .meta() to add descriptions and placeholders that appear in the admin UI:
import type { ContentTypeConfig } from "@btst/plugin-cms/api"
import { z } from "zod";
// ========== Product Schema ==========
// Use .meta({ fieldType: "..." }) to customize how fields render in the admin UI
export const ProductSchema = z.object({
name: z.string().min(1).meta({
description: "Product display name",
placeholder: "Enter product name..."
}),
description: z.string().meta({
description: "Full product description",
placeholder: "Describe this product...",
fieldType: "textarea", // Renders as a textarea
}),
price: z.coerce.number().min(0).meta({ placeholder: "0.00" }),
featured: z.boolean().default(false).meta({
description: "Show on homepage featured section",
fieldType: "switch", // Renders as a toggle switch
}),
category: z.enum(["Electronics", "Clothing", "Home", "Sports"]),
image: z.string().optional().meta({
description: "Product image",
fieldType: "file", // Renders as file upload (uses uploadImage override)
}),
});
// ========== Testimonial Schema ==========
export const TestimonialSchema = z.object({
author: z.string().min(1).meta({ placeholder: "Customer name" }),
company: z.string().optional().meta({ placeholder: "Company (optional)" }),
quote: z.string().meta({
description: "Customer testimonial text",
placeholder: "What did they say?",
fieldType: "textarea",
}),
rating: z.coerce.number().min(1).max(5).meta({
description: "Rating out of 5 stars"
}),
});
// One application-owned declaration can configure both CMS factories.
export const contentTypes = [
{
name: "Product",
slug: "product",
description: "Products for the store",
schema: ProductSchema,
},
{
name: "Testimonial",
slug: "testimonial",
description: "Customer testimonials",
schema: TestimonialSchema,
},
] satisfies ContentTypeConfig[];
// ========== Type Exports for Client Hooks ==========
/** Inferred type for Product data */
export type ProductData = z.infer<typeof ProductSchema>;
/** Inferred type for Testimonial data */
export type TestimonialData = z.infer<typeof TestimonialSchema>;
/**
* Type map for all CMS content types.
* Use this with CMS hooks for type-safe parsedData.
*/
export type CMSTypes = {
product: ProductData;
testimonial: TestimonialData;
};2. Add Plugin to Backend API
Register the CMS backend plugin with your content types:
On the first CMS operation or prefetch in each plugin instance, BTST synchronizes
the configured content types. Unchanged definitions do not write to the database
or change updatedAt. Changes to the name, description, schema, legacy field
configuration, or form version still update the stored definition. JSON object
metadata key order and whitespace do not count as schema changes. Array order
and schema properties order are preserved, since property order controls the
CMS form field order.
import { createBackendStack } from "@btst/stack/api"
import { cmsBackendPlugin } from "@btst/plugin-cms/api"
import { contentTypes } from "./cms-schemas"
const { handler, dbSchema } = createBackendStack({
basePath: "/api/data",
plugins: {
cms: cmsBackendPlugin({ contentTypes })
},
adapter: (db) => createMemoryAdapter(db)({})
})
export { handler, dbSchema }3. Add Plugin to Client
Register the CMS client plugin:
import { createClientStack } from "@btst/stack/client"
import { cmsClientPlugin } from "@btst/plugin-cms/client"
import { QueryClient } from "@tanstack/react-query"
import { contentTypes } from "./cms-schemas"
function getBaseURL(serverOrigin?: string) {
if (typeof window !== "undefined") return window.location.origin
return (
serverOrigin ||
process.env.BTST_SITE_URL ||
process.env.BASE_URL ||
"http://localhost:3000"
)
}
export const getStackClient = (
queryClient: QueryClient,
options?: { headers?: Headers; origin?: string },
) => {
const baseURL = getBaseURL(options?.origin)
return createClientStack({
api: {
baseURL,
basePath: "/api/data",
...(options?.headers ? { headers: options.headers } : {}),
},
site: { baseURL, basePath: "/pages" },
queryClient,
plugins: {
cms: cmsClientPlugin({ contentTypes })
}
})
}The backend HTTP catalog remains authoritative for content data. Passing the
shared declaration to cmsClientPlugin() preserves your application-defined
content-type order in the admin UI. Omit it when a managed or separately
deployed backend owns the catalog.
4. Configure the Provider
Pass the resolved client stack to the provider. Override inference comes from the registered CMS definition, so no manual override map or provider generic is needed:
import { nextRouter } from "@btst/stack/next"
const stack = getStackClient(queryClient, clientOrigins)
<StackProvider
stack={stack}
router={nextRouter()}
overrides={{
cms: {
uploadImage: async (file) => {
// Your image upload logic
return "https://example.com/image.png"
},
}
}}
>
{children}
</StackProvider>5. Import CSS
Add the CMS styles to your global CSS:
@import "@btst/plugin-cms/css";Supported Field Types
The CMS uses AutoForm to automatically render forms from Zod schemas. Use .meta({ fieldType: "..." }) on any field to customize its rendering:
| Zod Type | Default Handler | With fieldType Override |
|---|---|---|
z.string() | Input (text) | "textarea", "file" |
z.coerce.number() | Number input | - |
z.boolean() | Checkbox | "switch" |
z.coerce.date() | Date picker | - |
z.enum([...]) | Select dropdown | "radio" |
Adding UI Customization
Use .meta() to customize how fields appear and render. All field configuration is done directly in the Zod schema:
const ProductSchema = z.object({
name: z.string().min(1).meta({
description: "Product display name", // Shows as help text
placeholder: "Enter name..." // Input placeholder
}),
bio: z.string().meta({
description: "About this product",
fieldType: "textarea", // Renders as a multi-line textarea
}),
featured: z.boolean().default(false).meta({
fieldType: "switch", // Renders as a toggle switch instead of checkbox
}),
category: z.enum(["A", "B", "C"]).meta({
fieldType: "radio", // Renders as radio buttons instead of select
}),
});Image Upload Fields
To add an image upload field to your content type:
- Add an optional string field with
fieldType: "file"in your schema:
const ProductSchema = z.object({
name: z.string().min(1),
image: z.string().optional().meta({
description: "Product image URL",
fieldType: "file", // Renders as file upload
}),
// ...other fields
});- Provide
uploadImagein your StackProvider overrides:
// In your StackProvider overrides
cms: {
uploadImage: async (file: File) => {
// Upload to S3, Cloudinary, etc. and return the URL
const formData = new FormData();
formData.append("file", file);
const res = await fetch("/api/upload", { method: "POST", body: formData });
const { url } = await res.json();
return url;
},
// ...other overrides
}The built-in file component will use your uploadImage function to upload files and store the returned URL.
Repeating Groups (Arrays of Objects)
You can model repeating sub-records — variants, line items, blend components, FAQ entries, etc. — with z.array(z.object({...})). The admin renders each item as a sub-form inside an accordion with Add and Remove buttons, and useFieldArray from react-hook-form drives the row state.
.meta() placeholders, fieldType overrides, and custom fieldComponents (including "file" and "relation") are propagated into the array items, so you can build rich nested forms without writing a custom field component.
const ProductSchema = z.object({
name: z.string().min(1),
variants: z
.array(
z.object({
sku: z.string().meta({ placeholder: "SKU-001" }),
price: z.coerce.number().min(0).meta({ placeholder: "0.00" }),
notes: z.string().optional().meta({ fieldType: "textarea" }),
// Nested file uploads work when `uploadImage` is provided in overrides.
image: z.string().optional().meta({ fieldType: "file" }),
// Nested belongsTo relations render the searchable picker inside the row.
categoryId: z
.object({ id: z.string() })
.optional()
.meta({
fieldType: "relation",
relation: {
type: "belongsTo",
targetType: "category",
displayField: "name",
},
}),
}),
)
.default([])
.meta({ description: "Product variants" }),
});A few rules worth remembering:
- New rows are created with
append({})— fields with no default render empty until the user fills them in. - Inside item objects, do not name properties using reserved
FieldConfigItemkeys (label,description,inputProps,fieldType,renderParent,order). The admin will warn and skip those properties to avoid clobbering the array's own metadata. - Validation, defaults, and required-vs-optional behavior follow the inner Zod schema as usual.
Admin Routes
The CMS plugin provides these admin routes:
| Route | Description |
|---|---|
/cms | Dashboard - Grid of content types with item counts |
/cms/:typeSlug | Content list - Paginated table of items |
/cms/:typeSlug/new | Create new item |
/cms/:typeSlug/:id | Edit existing item |
Admin routes are automatically set to noindex for SEO. Don't include them in your public sitemap.
Page Component Overrides
You can replace any built-in admin page with your own React component using the optional pageComponents field in cmsClientPlugin(config). The built-in component is used as the fallback whenever an override is not provided. Overrides for parameterized routes receive the route context ({ params }) as props.
cmsClientPlugin({
// ... other config
pageComponents: {
// Replace the CMS dashboard page
dashboard: MyCustomDashboard,
// Replace the content list page — receives the route context as props
contentList: ({ params }) => (
<MyCustomContentList typeSlug={params.typeSlug} />
),
// Replace the new content page — receives the route context as props
newContent: ({ params }) => <MyCustomNewContent typeSlug={params.typeSlug} />,
// Replace the edit content page — receives the route context as props
editContent: ({ params }) => (
<MyCustomEditContent typeSlug={params.typeSlug} id={params.id} />
),
},
})Client Hooks
Fetch content data in your frontend pages using the provided hooks. All hooks support optional type generics for full type safety on parsedData.
Available Hooks
Query Hooks
| Hook | Description | Returns |
|---|---|---|
useContentTypes() | List all content types | { contentTypes, isLoading, error, refetch } |
useContentType(slug) | Get single content type by slug | { contentType, isLoading, error, refetch } |
useContent(typeSlug, options?) | List paginated items with infinite loading | { items, total, hasMore, loadMore, isLoadingMore, isLoading, error, refetch } |
useContentItem(typeSlug, id) | Get item by ID | { item, isLoading, error, refetch } |
useContentItemBySlug(typeSlug, slug) | Get item by slug | { item, isLoading, error, refetch } |
useContentItemPopulated(typeSlug, id) | Get item with relations populated | { item, isLoading, error, refetch } |
useContentByRelation(typeSlug, field, targetId) | Filter items by relation | { items, total, hasMore, loadMore, isLoadingMore, isLoading, error, refetch } |
Suspense Hooks
All query hooks have suspense variants for use with React Suspense:
| Hook | Description | Returns |
|---|---|---|
useSuspenseContentTypes() | List all content types (suspense) | { contentTypes, refetch } |
useSuspenseContent(typeSlug, options?) | List paginated items (suspense) | { items, total, hasMore, loadMore, isLoadingMore, refetch } |
useSuspenseContentItem(typeSlug, id) | Get item by ID (suspense) | { item, refetch } |
useSuspenseContentItemPopulated(typeSlug, id) | Get item with relations (suspense) | { item, refetch } |
useSuspenseContentByRelation(typeSlug, field, targetId) | Filter by relation (suspense) | { items, total, hasMore, loadMore, isLoadingMore, refetch } |
Mutation Hooks
| Hook | Description | Returns |
|---|---|---|
useCreateContent(typeSlug) | Create mutation | React Query mutation |
useUpdateContent(typeSlug) | Update mutation | React Query mutation |
useDeleteContent(typeSlug) | Delete mutation | React Query mutation |
Basic Usage (Without Type Safety)
import {
useContentTypes,
useContent,
useContentItem,
useContentItemBySlug
} from "@btst/plugin-cms/client/hooks"
// List all content types
function ContentTypesGrid() {
const { contentTypes, isLoading } = useContentTypes()
// ...
}
// List paginated content items
function ProductList() {
const { items, total, hasMore } = useContent("product", { limit: 20 })
// items[0].parsedData is Record<string, unknown>
}Type-Safe Usage (Recommended)
Import your CMSTypes type map and pass it to the hooks for full type inference on parsedData:
import { useContent, useContentItem, useContentItemBySlug } from "@btst/plugin-cms/client/hooks"
import type { CMSTypes } from "@/lib/cms-schemas"
// List products with type-safe parsedData
function ProductList() {
const { items, total, hasMore } = useContent<CMSTypes, "product">("product", {
limit: 20
})
return (
<ul>
{items.map((item) => (
<li key={item.id}>
{/* All fields are fully typed! */}
<h3>{item.parsedData.name}</h3>
<p>${item.parsedData.price}</p>
<span>{item.parsedData.category}</span>
{item.parsedData.featured && <Badge>Featured</Badge>}
</li>
))}
</ul>
)
}
// Get single item by ID with type safety
function ProductDetail({ id }: { id: string }) {
const { item, isLoading } = useContentItem<CMSTypes, "product">("product", id)
if (isLoading || !item) return <Skeleton />
return (
<div>
<h1>{item.parsedData.name}</h1>
<p>{item.parsedData.description}</p>
</div>
)
}
// Get single item by slug with type safety
function ProductPage({ slug }: { slug: string }) {
const { item } = useContentItemBySlug<CMSTypes, "product">("product", slug)
// item.parsedData.price is typed as number
}The type generics are optional for backward compatibility. Without them, parsedData defaults to Record<string, unknown>.
Mutations
Mutation hooks also support type generics for type-safe input data:
import {
useCreateContent,
useUpdateContent,
useDeleteContent
} from "@btst/plugin-cms/client/hooks"
import type { ProductData } from "@/lib/cms-schemas"
function CreateProductForm() {
// Type-safe mutation - TypeScript enforces correct data shape
const createProduct = useCreateContent<ProductData>("product")
const handleSubmit = async () => {
await createProduct.mutateAsync({
slug: "my-product",
data: {
name: "New Product",
description: "A great product",
price: 29.99,
featured: false,
category: "Electronics", // TypeScript autocompletes enum values!
}
})
}
}
function UpdateProductForm({ id }: { id: string }) {
const updateProduct = useUpdateContent<ProductData>("product")
const handleUpdate = async () => {
await updateProduct.mutateAsync({
id,
data: { data: { name: "Updated Name", price: 39.99 } }
})
}
}Content views
Pass view: "content" to collection, ID, and slug reads to receive exactly id, slug, parsedData, createdAt, and updatedAt. List responses keep their items, total, limit, and offset envelope. Every parsed content property remains available, including a property named author; only editor metadata and the duplicate raw JSON string are omitted. Calls without this option retain their existing responses.
const page = await myStack.forRequest(request).operations.cms.listContentItems({
typeSlug: "article",
query: { view: "content", limit: 10, search: "release" },
})
const item = await myStack.trusted.cms.getContentItem({
typeSlug: "article",
id: articleId,
view: "content",
})Content view retains the same authorization checks. For a content type with an
explicit publication policy, it also excludes unpublished
and future-scheduled entries. Request operations still require the same collection
or record access and content-type metadata access. trusted.cms is for explicitly
trusted jobs. Lower-level adapter-first getters skip request authorization and
lifecycle hooks; their caller must enforce access control:
import {
getAllContentItems,
getContentItemById,
getContentItemBySlug,
} from "@btst/plugin-cms/api"
const page = await getAllContentItems(adapter, "article", {
view: "content", limit: 10, offset: 0,
})
const byId = await getContentItemById(adapter, articleId, { view: "content" })
const bySlug = await getContentItemBySlug(adapter, "article", "release-notes", {
view: "content",
})HTTP uses the existing routes. Use GET /content/article?view=content&limit=10 for a collection, GET /content/article/:id?view=content for an ID, or GET /content/article?slug=release-notes&view=content&limit=1 for a slug-filtered list. Invalid view values return validation errors. Missing-record and malformed stored JSON behavior is unchanged. Dates retain their existing ISO string representation.
The existing hooks accept the same option, including their suspense variants:
const { items } = useContent("article", { view: "content", limit: 10 })
const { item } = useContentItem("article", articleId, { view: "content" })
const bySlug = useContentItemBySlug("article", "release-notes", { view: "content" })Full and content responses use distinct cache entries. Content mutations refresh affected list, ID, and slug entries, and full mutation responses seed only the compatible full detail entry. Existing createCMSQueryKeys reads also accept the option. SSG can prefetch a matching view and list size/search:
await myStack.raw.cms.prefetchForRoute("contentList", queryClient, {
typeSlug: "article", view: "content", limit: 10,
})
await myStack.raw.cms.prefetchForRoute("editContent", queryClient, {
typeSlug: "article", id: articleId, view: "content",
})CMSReadOptions, SerializedContentItemContent, and CMSContentItemResult are exported from the CMS API and client entries. Statically known content reads omit editor fields from their TypeScript results; dynamic view choices have a union result. Reducing the returned envelope does not provide database JSON-field projection: the stored JSON may still be read and parsed.
Selecting content properties
Add fields with view: "content" to select declared top-level properties inside parsedData. The same options work on collection, ID, slug, direct-relation, and inverse-relation item reads. Identity and timestamps are always returned. Omit fields to retain all parsed content.
const cards = await myStack.forRequest(request).operations.cms.listContentItems({
typeSlug: "article",
query: { view: "content", fields: ["title", "summary"], search: "release" },
})
const related = await getContentItemsByRelation(adapter, "article", {
field: "authorId", targetId: authorId, view: "content", fields: ["title", "summary"],
limit: 10, offset: 0,
})
const item = await getContentItemById(adapter, articleId, {
view: "content", fields: ["title"],
})Selections are literal names, not nested paths. A declared name such as "contact.name", "display, label", or a Unicode name is valid. Selecting an object or array returns that entire value. Absent optional properties remain absent and explicit null remains null; a content property named author has no special treatment. Search, slug filters, relation matching, ordering and totals run before projection, so omitted content can still determine matches.
HTTP encodes the array as JSON in one query parameter with normal URL encoding:
const query = new URLSearchParams({
view: "content", fields: JSON.stringify(["title", "contact.name"]),
})
const response = await fetch(`/api/data/content/article?${query}`)Malformed JSON, non-array/non-string selections, an empty array, unknown properties, nested traversal names absent from the schema, and fields without content view are rejected. Operations use the existing validation error response; lower-level getters throw for invalid selections. Existing access checks and malformed stored JSON failures remain in effect.
const cards = useContent("article", {
view: "content", fields: ["title", "summary"], limit: 10,
})
const item = useContentItem("article", articleId, { view: "content", fields: ["title"] })
const related = useContentByRelation("article", "authorId", authorId, {
view: "content", fields: ["title", "summary"],
})The existing picker helper supports the same options for both search results and selected-ID preloads:
const picker = useContentOptions({
targetType: "article", value: selectedArticleIds,
view: "content", fields: ["title", "summary"],
getOptionLabel: (item) => String(item.parsedData.title),
})Omitting the picker options preserves full records for existing relation fields. Projected preloads keep the selected output shape even when a full detail response is already cached.
Different selections and page sizes have distinct cache identities; duplicate and reordered field names share an identity. Mutations invalidate projected variants, and a full mutation result seeds only the full detail cache. createCMSQueryKeys and applicable prefetchForRoute calls accept the same options, normalize the same field sets, serialize dates, and retain the existing infinite-query hydration envelope.
CMSContentFields and CMSSelectedData are exported alongside the read option/result types. Literal selections narrow the returned properties; dynamic string arrays yield a partial data shape. Runtime schemas still determine valid field names and value types. With an explicit existing data map, supply the selection tuple to retain exact selected property types:
type ContentTypes = { article: { title: string; summary?: string; body: string } }
const cards = useContent<ContentTypes, "article", readonly ["title", "summary"]>(
"article", { view: "content", fields: ["title", "summary"] },
)
// cards.items contain title and optional summary, without body or editor metadata.Projection reduces returned payloads. It does not guarantee database-level JSON-field projection: stored JSON may still need to be fetched and parsed, and relation ID/metadata scans can grow with cardinality.
Backend Hooks
Customize CMS behavior with backend hooks:
cmsBackendPlugin({
contentTypes: [...],
hooks: {
onBeforeCreateContent: async (data, context) => {
console.log("Creating item in", context.typeSlug)
// `data` is validated and canonical. Throw to deny.
},
onAfterCreateContent: async (item, context) => {
console.log("Created:", item.slug)
// Trigger webhooks, notifications, etc.
},
onBeforeUpdateContent: async (id, data, context) => {
// `data` is the complete merged, validated record. Throw to deny.
},
onAfterUpdateContent: async (item, context) => {
// ...
},
onBeforeDeleteContent: async (id, context) => {
// Throw to deny: throw new Error("Cannot delete published content")
},
onAfterDeleteContent: async (id, context) => {
// ...
},
onErrorExecuteContentOperation: async (error, operation, context) => {
console.error(`CMS ${operation} error:`, error.message)
},
},
})A plain error thrown by onBeforeCreateContent, onBeforeUpdateContent, or
onBeforeDeleteContent denies the request with HTTP 403. Create and update hooks run
before the parent or any inline related record is written, and no mutation is
committed when a before hook denies the operation.
CMS lifecycle names use the action-first onBefore<Action><Entity>,
onAfter<Action><Entity>, and onError<Action><Entity> grammar. The existing
aggregate error phase remains one callback; its operation argument identifies
the failed create, update, delete, list, or get operation.
| Removed name | Canonical name |
|---|---|
onBeforeCreate | onBeforeCreateContent |
onAfterCreate | onAfterCreateContent |
onBeforeUpdate | onBeforeUpdateContent |
onAfterUpdate | onAfterUpdateContent |
onBeforeDelete | onBeforeDeleteContent |
onAfterDelete | onAfterDeleteContent |
onError | onErrorExecuteContentOperation |
Type Safety
The CMS plugin provides end-to-end type safety from schema definition to frontend rendering:
1. Schema Definition → Backend Validation
Zod schemas defined in cms-schemas.ts are used by the backend to validate all content operations:
// lib/cms-schemas.ts
export const ProductSchema = z.object({
name: z.string().min(1),
price: z.coerce.number().min(0),
});2. Type Map → Client Hooks
Export inferred types and a type map for client-side type safety:
// lib/cms-schemas.ts
export type ProductData = z.infer<typeof ProductSchema>;
export type CMSTypes = { product: ProductData };3. Type-Safe Data Access
Use the type map with hooks to get fully typed parsedData:
import { useContent } from "@btst/plugin-cms/client/hooks"
import type { CMSTypes } from "@/lib/cms-schemas"
function ProductList() {
const { items } = useContent<CMSTypes, "product">("product")
// ✅ TypeScript knows all field types
items[0].parsedData.name // string
items[0].parsedData.price // number
// ❌ TypeScript error: Property 'invalid' does not exist
items[0].parsedData.invalid
}4. Schema Changes Trigger Compile Errors
When you update a schema, TypeScript shows errors everywhere the types are used:
// Adding a new required field to ProductSchema...
const ProductSchema = z.object({
name: z.string(),
price: z.number(),
sku: z.string(), // New field
});
// ...triggers TypeScript errors in components
<span>{item.parsedData.sku}</span> // ✅ Now works
createProduct.mutate({
slug: "x",
data: { name: "X", price: 10 } // ❌ Error: missing 'sku'
})This ensures developers catch schema changes at compile time rather than in production.
API Endpoints
The CMS plugin exposes these REST endpoints:
| Endpoint | Method | Description |
|---|---|---|
/content-types | GET | List all content types with item counts |
/content-types/:slug | GET | Get single content type by slug |
/content/:typeSlug | GET | List items (query: slug, limit, offset) |
/content/:typeSlug | POST | Create item |
/content/:typeSlug/:id | GET | Get single item |
/content/:typeSlug/:id | PUT | Update item |
/content/:typeSlug/:id | DELETE | Delete item |
/content/:typeSlug/:id/populated | GET | Get item with relations populated |
/content/:typeSlug/by-relation | GET | Filter by relation (query: field, targetId) |
/content-types/:slug/inverse-relations | GET | Inspect inverse relation definitions |
/content-types/:slug/inverse-relations/:sourceType | GET | List inverse relation items |
Authorization & Lifecycle Hooks
CMS owns a browser-safe, schema-backed permission catalog. Define one rule set against that catalog, then bind it to a server identity adapter and a browser identity adapter. The built-in CMS routes and the backend operations use the same descriptors—there is no second list of resource/action strings to keep in sync.
import { z } from "zod"
import { defineAuthorization } from "@btst/stack/authorization"
import { cmsPermissions } from "@btst/plugin-cms/permissions"
export const authorization = defineAuthorization({
identity: z.object({
id: z.string(),
role: z.enum(["editor", "admin"]),
}),
permissions: [cmsPermissions] as const,
rules: ({ cms }) => [
// Public record responses embed their content-type schema, so both reads
// must be declared public. Omit either rule to deny that response.
cms.record.read.allow(),
cms.contentType.read.allow(),
cms.record.create.when(({ identity }) => identity !== null),
cms.record.update.when(
({ identity, facts }) =>
identity?.role === "admin" || identity?.id === facts.authorId,
),
cms.record.delete.when(
({ identity, facts }) =>
identity?.role === "admin" || identity?.id === facts.authorId,
),
],
})Bind the same value on the backend. HTTP routes and request-scoped calls resolve the identity, derive trusted facts from the database, evaluate the rule, and only then enter CMS lifecycle hooks and mutation code.
import { createServerAuth } from "@btst/stack/authorization/server"
import { authorization } from "./authorization"
const auth = createServerAuth({
authorization,
getIdentity: async ({ request }) => {
const session = await getSession(request.headers)
return session?.user ?? null
},
})
export const myStack = createBackendStack({
basePath: "/api/data",
plugins: { cms: cmsBackendPlugin({ contentTypes }) },
adapter: (db) => createMemoryAdapter(db)({}),
auth,
})The exact cmsPermissions descriptors are evaluated before lifecycle hooks. Compound inline-create, existing-relation, populated-record, and inverse-relation checks evaluate every server-derived target or source separately, so a secondary record cannot be exposed or mutated through a permitted primary record. Record responses embed their content-type schema, so
record list, detail, create, update, populated, and relation-list operations
also require cms.contentType.read for every embedded type. Relation filters
derive the target type from the configured relation field and authorize the
authoritative target record before reading junction rows.
Bind it in the browser for immediate presentation checks. Browser facts only control what is shown; they are never trusted by the backend.
import { createClientAuth } from "@btst/stack/authorization/client"
import { authorization } from "@/lib/authorization"
const auth = createClientAuth({
authorization,
getIdentity: () => getBrowserSession()?.user ?? null,
})
<StackProvider
stack={stack}
auth={auth}
initialIdentity={initialIdentity}
// router, overrides, ...
>
{children}
</StackProvider>CMS permission catalog
| Descriptor | Facts | Backend operations |
|---|---|---|
cms.contentType.read | contentType? | List content types, get a content type, inspect inverse relation definitions |
cms.record.read | contentType, scope: "collection" | "record", recordId?, authorId?, view? | List, get, populate, and relation reads |
cms.record.create | contentType | Create a record |
cms.record.update | contentType, recordId, authorId? | Update a record |
cms.record.delete | contentType, recordId, authorId? | Delete a record |
The backend reloads the content type and record before it derives
contentType, scope, recordId, and authorId; client-supplied ownership,
lookup scope, or type claims cannot authorize a write. A by-slug lookup uses
scope: "record" even when no matching record exists, so an explicitly public
detail rule can return a not-found result without exposing the collection.
Rules are boolean operation checks. If your
application needs tenant or row filtering, scope the backend query itself
rather than treating a boolean rule as a data filter.
For explicitly configured publication types, filtered content-view reads also
derive view: "content". Editor reads and unconfigured types omit this fact.
Use it to grant public projections separately from full editor records.
The content-type catalog includes itemCount, so listing it also authorizes a
collection-scoped cms.record.read for every counted content type. If any
collection is denied, the operation fails without returning partial counts.
Server operation surfaces
The same operation pipeline backs all authoritative application surfaces:
// Identity comes from this request; authorization is enforced.
await myStack.forRequest(request).operations.cms.updateContentItem({
typeSlug: "product",
id: productId,
body: { data: { name: "Updated" } },
})
// Trusted application code skips only user authorization. Validation,
// fact derivation, execution, and lifecycle hooks still run.
await myStack.trusted.cms.deleteContentItem({
typeSlug: "product",
id: productId,
})myStack.raw.cms contains only the SSG prefetchForRoute helper. Use forRequest(request).operations.cms for request work and trusted.cms for explicitly trusted jobs; both retain validation and lifecycle behavior.
Inline _new relation values are compound writes. Request-scoped create and
update operations authorize cms.record.create for every server-derived target
content type before hooks run, then commit the parent, related records, and
relation rows atomically. Existing { id } relation values are resolved against
the configured target content type and require cms.record.read for the
authoritative target facts. The operation rejects wrong-type IDs and rechecks
target ownership before the transaction writes a relation. Trusted
trusted.cms calls skip those user checks but keep the same validation and
transaction lifecycle.
Compound reads fail closed too. A populated-record operation authorizes every
related target record before returning it, and inverse-relation metadata
authorizes each referring source content type before exposing its name or
fields. When inverse metadata includes counts for an itemId, it also
authorizes that target record and each counted source collection before reading
relation rows. Listing the records for an inverse relation likewise authorizes
the source collection and target record, and rederives the requested relation
field from the current content-type schemas.
Loader hooks may still prepare data and report failures, but they are not an
authorization boundary. onErrorLoad is reporting-only: callback errors are
contained and the loader never rejects, so it cannot perform throwing framework
redirects. Use onRouteRender and onRouteError for presentation lifecycle and
reporting.
Custom Field Components
You can provide custom field components via the fieldComponents override. This allows you to:
- Override built-in types (like "file") with custom implementations
- Add custom field types for specialized inputs (rich text editors, color pickers, etc.)
Using fieldComponents Override
The fieldComponents property maps field type names to React components:
import type { CMSPluginOverrides, AutoFormInputComponentProps } from "@btst/plugin-cms/client"
// Define a custom component
function MyColorPicker({ field, label, isRequired, fieldConfigItem }: AutoFormInputComponentProps) {
return (
<div className="space-y-2">
<label className="text-sm font-medium">
{label}
{isRequired && <span className="text-destructive"> *</span>}
</label>
<input
type="color"
value={field.value || "#000000"}
onChange={(e) => field.onChange(e.target.value)}
className="h-10 w-full cursor-pointer"
/>
{fieldConfigItem?.description && (
<p className="text-sm text-muted-foreground">{String(fieldConfigItem.description)}</p>
)}
</div>
)
}
// In your StackProvider overrides:
cms: {
fieldComponents: {
// Override the built-in "file" type
file: ({ field, label, isRequired }) => (
<MyCustomFileUpload
value={field.value}
onChange={field.onChange}
label={label}
required={isRequired}
/>
),
// Add a custom "color" type
color: MyColorPicker,
// Add a custom "richText" type
richText: ({ field, label }) => (
<MyRichTextEditor value={field.value} onChange={field.onChange} label={label} />
),
},
// ...other overrides
}Registering Custom Field Types
To use a custom field type, add it to your Zod schema with .meta({ fieldType: "..." }):
// In your schema definition
const ProductSchema = z.object({
name: z.string().min(1),
primaryColor: z.string().optional().meta({
description: "Brand color",
fieldType: "color", // Uses custom "color" component from fieldComponents
}),
longDescription: z.string().optional().meta({
description: "Rich text content",
fieldType: "richText", // Uses custom "richText" component from fieldComponents
}),
});AutoFormInputComponentProps
Custom components receive these props:
| Prop | Type | Description |
|---|---|---|
field | ControllerRenderProps | React Hook Form field controller with value and onChange |
label | string | The field label (derived from schema key) |
isRequired | boolean | Whether the field is required |
fieldConfigItem | FieldConfigItem | Field config including description, inputProps, etc. |
fieldProps | object | Additional props from inputProps in fieldConfig |
zodItem | ZodAny | The Zod schema for this field |
Using the Built-in CMSFileUpload
The plugin exports CMSFileUpload for consumers who want to use or extend the default file upload:
import { CMSFileUpload } from "@btst/plugin-cms/client"
// In your fieldComponents override
cms: {
fieldComponents: {
// Use the built-in component with your upload function
file: (props) => (
<CMSFileUpload {...props} uploadImage={myUploadFn} />
),
// Or create a wrapper with custom styling
customImage: (props) => (
<div className="my-custom-wrapper">
<CMSFileUpload {...props} uploadImage={myUploadFn} />
</div>
),
},
}When a custom component is provided for a field type via fieldComponents, it takes precedence over the built-in component. This allows you to completely customize how any field type is rendered.
Data Relationships
The CMS plugin supports relationships between content types, enabling you to build directories, blogs with tags, or any relational data structure. Relationships are defined in your Zod schemas using .meta({ fieldType: "relation", relation: {...} }).
Defining Relationships
Add a relation field to your schema:
import { z } from "zod";
// Category schema (the target of the relation)
export const CategorySchema = z.object({
name: z.string().min(1).meta({
description: "Category name",
placeholder: "Enter category name...",
}),
description: z.string().optional().meta({
description: "Optional category description",
fieldType: "textarea",
}),
color: z.string().optional().meta({
description: "Category color (hex code)",
placeholder: "#3b82f6",
}),
});
// Resource schema with a manyToMany relation to categories
export const ResourceSchema = z.object({
name: z.string().min(1).meta({
description: "Resource name",
placeholder: "Enter resource name...",
}),
description: z.string().meta({
description: "Full resource description",
fieldType: "textarea",
}),
website: z.string().url().optional().meta({
description: "Website URL",
placeholder: "https://example.com",
}),
// Relation field - manyToMany with categories
categoryIds: z
.array(z.object({ id: z.string() }))
.default([])
.meta({
fieldType: "relation",
relation: {
type: "manyToMany",
targetType: "category", // Slug of the target content type
displayField: "name", // Field to display in the selector
creatable: true, // Allow creating new categories inline
},
}),
});
export type CategoryData = z.infer<typeof CategorySchema>;
export type ResourceData = z.infer<typeof ResourceSchema>;
export type CMSTypes = {
category: CategoryData;
resource: ResourceData;
};Relationship Types
| Type | Description | Schema Format | Use Case |
|---|---|---|---|
belongsTo | Single reference to another item | z.object({ id: z.string() }).optional() | Comment → Resource (one-to-many inverse) |
hasMany | Multiple references | z.array(z.object({ id: z.string() })) | Author → Posts |
manyToMany | Many-to-many via junction table | z.array(z.object({ id: z.string() })) | Resource ↔ Categories |
belongsTo vs manyToMany: Use belongsTo when an item references a single parent (e.g., a Comment belongs to one Resource). Use manyToMany when items can have multiple relationships (e.g., a Resource can have many Categories).
belongsTo Example (One-to-Many)
For one-to-many relationships, the "many" side uses belongsTo to reference the "one" side:
// Resource Schema - the "one" side
export const ResourceSchema = z.object({
name: z.string().min(1),
description: z.string(),
// ... other fields
});
// Comment Schema - the "many" side (belongs to Resource)
export const CommentSchema = z.object({
author: z.string().min(1).meta({
description: "Comment author name",
placeholder: "Your name...",
}),
content: z.string().min(1).meta({
description: "Comment content",
placeholder: "Write your comment...",
fieldType: "textarea",
}),
// belongsTo relation - links to a single Resource
// Unlike manyToMany (array), belongsTo stores a single { id: string }
resourceId: z.object({ id: z.string() }).optional().meta({
fieldType: "relation",
relation: {
type: "belongsTo",
targetType: "resource",
displayField: "name",
},
}),
});The admin UI renders belongsTo fields as a single-select dropdown instead of a multi-select.
RelationConfig Properties
| Property | Type | Description |
|---|---|---|
type | "belongsTo" | "hasMany" | "manyToMany" | The relationship type |
targetType | string | Slug of the target content type |
displayField | string | Field to show in the selector (e.g., "name", "title") |
creatable | boolean | Allow creating new related items inline (optional, default: false) |
Relation Hooks
Use these hooks to fetch content with populated relations:
import {
useContentItemPopulated,
useContentByRelation
} from "@btst/plugin-cms/client/hooks"
import type { CMSTypes } from "@/lib/cms-schemas"
// Get a single resource with its related categories populated
function ResourceDetail({ id }: { id: string }) {
const { item, isLoading } = useContentItemPopulated<CMSTypes, "resource">(
"resource",
id
)
if (isLoading || !item) return <Skeleton />
return (
<div>
<h1>{item.parsedData.name}</h1>
<p>{item.parsedData.description}</p>
{/* Related categories are populated in _relations */}
<div className="flex gap-2">
{item._relations?.categoryIds?.map((category) => (
<span key={category.id} className="badge">
{category.parsedData.name}
</span>
))}
</div>
</div>
)
}
// Get resources filtered by a specific category
function CategoryResources({ categoryId }: { categoryId: string }) {
const { items, isLoading } = useContentByRelation<CMSTypes, "resource">(
"resource",
"categoryIds", // Field name containing the relation
categoryId // ID of the related category
)
return (
<ul>
{items.map((resource) => (
<li key={resource.id}>{resource.parsedData.name}</li>
))}
</ul>
)
}Inline Creation
When creatable: true is set in the relation config, users can create new related items directly from the relation selector. A modal form will appear allowing them to create a new item (e.g., a new category) without leaving the current form.
categoryIds: z
.array(z.object({ id: z.string() }))
.default([])
.meta({
fieldType: "relation",
relation: {
type: "manyToMany",
targetType: "category",
displayField: "name",
creatable: true, // Shows "Create new..." option in selector
},
}),Inverse Relations Panel
When editing content in the CMS admin, an Inverse Relations Panel automatically appears below the form. This panel shows all items that reference the current item via belongsTo relations.
For example, when editing a Resource, the panel displays all Comments that belong to that Resource:
┌─────────────────────────────────────────────┐
│ 📝 Comments (3) [▼] │
├─────────────────────────────────────────────┤
│ • "Great resource!" by John [Edit] [🗑] │
│ • "Very helpful" by Jane [Edit] [🗑] │
│ • "Thanks!" by Bob [Edit] [🗑] │
│ │
│ [+ Add Comment] │
└─────────────────────────────────────────────┘The panel:
- Auto-discovers content types with
belongsTorelations pointing to the current type - Shows a count and list of related items with edit/delete links
- Provides an "Add" button to create new related items with the relation pre-filled
Relation API Endpoints
Direct and inverse relation-item reads return { items, total, limit, offset }.
total counts unique matching source items before pagination, even when the
junction table contains duplicate references. Results sort by createdAt
descending, then ID descending for equal timestamps. Both endpoints accept
limit (default 20, bounded by maxPageSize) and offset (default 0).
Both reads also accept view: "content". Each item then contains exactly id,
slug, parsedData, createdAt, and updatedAt, inside the same page envelope.
Omitting view retains full items. Relation discovery, summaries, and counts keep
their existing response shapes. Content view retains the same source, target,
and content-type access checks and schema/target race protections.
// Request-scoped reads preserve collection, type, and target-record access checks.
const page = await myStack.forRequest(request).operations.cms.listContentByRelation({
typeSlug: "article",
query: { field: "authorId", targetId: authorId, limit: 20, offset: 20, view: "content" },
})
const inversePage = await myStack.forRequest(request).operations.cms.listInverseRelationItems({
slug: "author", sourceType: "article",
query: { fieldName: "authorId", itemId: authorId, limit: 20, offset: 20, view: "content" },
})
// Lower-level reads for callers that manage validation and access control.
import { getContentItemsByRelation } from "@btst/plugin-cms/api"
const serverPage = await getContentItemsByRelation(adapter, "article", {
field: "authorId", targetId: authorId, limit: 20, offset: 20, view: "content",
})The adapter-first getter does not authorize requests, validate the configured
relation or target access, or run lifecycle hooks. Use request operations for
request work and myStack.trusted.cms for validated, lifecycle-aware trusted jobs.
It returns an empty page for a missing source type or no matching items.
Relation rows are scanned in batches of 500 ordered by source ID. Duplicate
sources are counted once, including duplicates spanning a batch boundary. Item
metadata is fetched in bounded ID batches, and full item payloads are fetched only
for the requested page. Configured public reads exclude records with a non-null
publishAt in the database before inspecting publication state in JSON. Only IDs
and creation times are retained for sorting after that inspection.
The CMS schema declares non-unique indexes on contentRelation:
(targetId, fieldName, sourceId)supports the reverse lookup and source ordering.(sourceId, fieldName)supports source-side population and relation replacement.
Existing SQL applications must generate and review the schema changes with
npx @btst/codegen generate, then apply a migration using their ORM's normal
workflow (for Prisma: prisma migrate dev locally and prisma migrate deploy for
deployment). Updating the plugin alone does not install indexes in an existing
database. Preserve application-owned tables and relation names when reviewing
generated output. The separate Prisma duplicate-reference generator defect
can require preserving the existing valid source/target relation declarations.
Compound index generation is supported by the pinned DB CLI for Prisma and Drizzle. SQL index choice depends on the engine, collation and data distribution; the memory adapter does not implement physical indexes. These indexes do not index publication state inside the JSON string or order content by creation time. Internal ID and metadata work still grows with matching relation cardinality on every page. The portable fallback preserves exact totals and creation-time/ID ordering in JavaScript; database-side filtered relation pagination needs the capabilities tracked in BTST/db #55. See the reproducible benchmark for measurements and the PostgreSQL query prototype.
const articles = useContentByRelation("article", "authorId", authorId, { limit: 10, view: "content" })
// articles.loadMore() fetches the next page; different page sizes use distinct caches.
const comments = useInverseRelationItems({
contentTypeSlug: "article", sourceType: "comment", itemId: articleId, fieldName: "articleId",
}, { limit: 10, offset: 20, view: "content" })GET /api/data/content/article/by-relation?field=authorId&targetId=author-1&limit=10&view=content
GET /api/data/content-types/author/inverse-relations/article?fieldName=authorId&itemId=author-1&limit=10&offset=20&view=contentFull and content relation pages use distinct cache entries, including page size
and inverse offsets. The existing createCMSQueryKeys factory carries these
same view/page identities for SSR hydration. Direct relation hydration uses an
infinite-query { pages, pageParams } envelope; inverse hydration uses the page.
Content create, update, and delete mutations refresh affected direct and inverse
relation-item queries and inverse summaries.
| Endpoint | Method | Description |
|---|---|---|
/content/:typeSlug/:id/populated | GET | Get item with relations populated |
/content/:typeSlug/populated | GET | List items with relations populated |
/content/:typeSlug/by-relation | GET | Filter by relation (query: field, targetId) |
/content-types/:slug/inverse-relations | GET | Get content types that reference this type (query: itemId optional) |
/content-types/:slug/inverse-relations/:sourceType | GET | Get items referencing this item (query: itemId, fieldName) |
Example API calls:
# Get resource with populated categories
curl /api/data/content/resource/abc123/populated
# Get all resources linked to a specific category
curl /api/data/content/resource/by-relation?field=categoryIds&targetId=cat456
# Get inverse relations for a resource (what types reference it)
curl /api/data/content-types/resource/inverse-relations?itemId=abc123
# Get all comments for a specific resource
curl /api/data/content-types/resource/inverse-relations/comment?itemId=abc123&fieldName=resourceIdCreating Items with Relations via API
When creating content items via API, pass relation values based on the relation type:
manyToMany / hasMany Relations (Array)
// Link to existing categories (array format)
await fetch("/api/data/content/resource", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
slug: "my-resource",
data: {
name: "My Resource",
description: "A great resource",
categoryIds: [
{ id: "existing-category-id-1" },
{ id: "existing-category-id-2" },
],
},
}),
});
// Create new categories inline using _new flag
await fetch("/api/data/content/resource", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
slug: "my-resource",
data: {
name: "My Resource",
description: "A great resource",
categoryIds: [
{ id: "existing-category-id" },
{ _new: true, data: { name: "New Category", color: "#10b981" } },
],
},
}),
});_new is strict creation, not an upsert or an alternate way to reference an
existing record. BTST derives a slug from the inline data; if that slug already
exists for the target content type or occurs twice in the same request, the
operation returns HTTP 409 with code RELATED_RECORD_SLUG_CONFLICT. Pass
{ id: "existing-record-id" } when you intend to link an existing record.
belongsTo Relations (Single Object)
// Create comment linked to a resource (single object format)
await fetch("/api/data/content/comment", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
slug: "my-comment",
data: {
author: "John Doe",
content: "Great resource!",
resourceId: { id: "existing-resource-id" }, // Single object, not array
},
}),
});Building a Directory
Here's a complete example of building a resource directory with categories:
"use client"
import { useContent } from "@btst/plugin-cms/client/hooks"
import type { CMSTypes } from "@/lib/cms-schemas"
export default function DirectoryPage() {
const { items: resources } = useContent<CMSTypes, "resource">("resource")
const { items: categories } = useContent<CMSTypes, "category">("category")
const [search, setSearch] = useState("")
const filteredResources = resources.filter((r) =>
r.parsedData.name.toLowerCase().includes(search.toLowerCase())
)
return (
<div className="flex gap-8">
{/* Sidebar with categories */}
<aside className="w-64">
<h3>Categories</h3>
<ul>
{categories.map((cat) => (
<li key={cat.id}>
<Link href={`/directory/category/${cat.id}`}>
{cat.parsedData.name}
</Link>
</li>
))}
</ul>
</aside>
{/* Main content */}
<main className="flex-1">
<input
type="text"
placeholder="Search resources..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<div className="grid grid-cols-3 gap-4">
{filteredResources.map((resource) => (
<Link key={resource.id} href={`/directory/${resource.id}`}>
<h3>{resource.parsedData.name}</h3>
<p>{resource.parsedData.description}</p>
</Link>
))}
</div>
</main>
</div>
)
}Revision history and scheduling
The entry editor's Revision history drawer lists saved versions, newest first, with a timestamp, writer identity (or System for trusted jobs), slug, schedule, and field snapshot. Expand a version and choose Restore this version to replace the active entry. The confirmation warns that unsaved editor changes will be discarded. Restoring keeps all existing revisions and appends a new one.
Successful content creation, updates (including schedule-only updates), rollback,
inline related-item creation, and createCMSContentItem() append an immutable
contentRevision row in the same transaction as the content write. Rejected
validation, authorization, duplicate slugs, and before-hook failures do not append
revisions. There is no operation to edit or individually delete a revision;
revision rows cascade when their content item is deleted.
School course creation, edits and archival, and automatic Job Board archival
also append snapshots in their write transactions. Custom lower-level writers
can call recordContentRevision(tx, item, authorId?) from
@btst/plugin-cms/api after writing the item in the same transaction; callers
own validation, authorization and lifecycle hooks.
publishAt is optional top-level scheduling metadata, separate from the
content type's data. The editor accepts local date/time and sends an ISO
timestamp with its time-zone offset converted to UTC. HTTP and operation inputs
accept ISO timestamps with a time-zone offset; omit the property to preserve the
schedule on update, or pass null to clear it. Serialized items and revisions
return ISO strings or null.
Saving other editor fields preserves the original timestamp's precision until
the schedule control is edited.
Saving a schedule does not change the item's publication state. Automatic publication requires an explicit content-type policy and an application-owned scheduler, described below. Clearing a schedule cancels automatic publication; it does not publish or unpublish the item. Without a publication policy, the field remains scheduling metadata and existing read behavior is unchanged, including UI Builder, Ecommerce, School, and Job Board.
const cms = myStack.forRequest(request).operations.cms;
const item = await cms.createContentItem({
typeSlug: "article",
body: {
slug: "launch",
data: { title: "Launch announcement" },
publishAt: "2030-12-05T14:30:00Z",
},
});
const history = await cms.listContentRevisions({
typeSlug: "article", id: item.id, offset: 0,
});
await cms.restoreContentRevision({
typeSlug: "article", id: item.id, revisionId: history.items[0].id,
});GET /content/:typeSlug/:id/revisions?offset=0 returns { items, total } in
pages of 20. POST /content/:typeSlug/:id/revisions/:revisionId/restore returns
the active item. These paths are relative to the stack API base path.
Listing requires cms.record.read for the authoritative record plus
cms.contentType.read. Restoring requires the existing record update and read
permissions, content-type read, and permission to read any restored relation
targets. Rollback runs the normal update lifecycle hooks and validates against
the current content-type schema. Incompatible old schemas, missing relation
targets, and slug conflicts fail without changing the active item.
Client hooks useContentRevisions(typeSlug, id, enabled?) and
useRestoreContentRevision() are exported from @btst/plugin-cms/client/hooks.
Restore refreshes content, revision history, and relation queries. The existing
create/update hooks accept optional publishAt alongside slug and data.
Scheduled publication
Publication is opt-in for each content type. Declare the top-level content field
and the two values that mean scheduled and published; CMS does not assume a
data.status convention:
import type { ContentTypeConfig } from "@btst/plugin-cms/api";
import { z } from "zod";
export const article = {
name: "Article",
slug: "article",
schema: z.object({
title: z.string().min(1),
publicationState: z.enum(["draft", "queued", "live"]),
}),
publication: {
stateField: "publicationState",
scheduledValue: "queued",
publishedValue: "live",
},
} satisfies ContentTypeConfig;The field must exist in the schema and both distinct values must validate against it. Only explicitly configured types participate. Existing unconfigured types keep their current scheduling, read, and write behavior.
To schedule an article, save both data.publicationState: "queued" and a
top-level publishAt ISO timestamp. An item in draft is not eligible for
dispatch merely because it has a timestamp. A queued item stays hidden after
its due time until dispatch successfully changes its state to live and clears
its schedule. Changing the timestamp reschedules it; publishAt: null cancels
it without changing publicationState. Omitting publishAt on an update
preserves the existing schedule. The editor's schedule control uses the browser's
local time zone; API timestamps require an explicit offset or Z and are stored
and compared as UTC instants. Applications should choose an offset explicitly
around daylight-saving transitions.
Public and editor reads
For configured types, use view: "content" for public list, ID, slug, search,
relation-item, and SSG reads. The publication policy is applied before pagination
and totals. Only items in the published state with no outstanding schedule are
visible, even for a trusted content-view read. Any non-null publishAt keeps an
item private, including a past timestamp on an item already in the published
state. To publish it manually, clear the schedule and set the published state.
Hidden detail reads behave like missing records.
The default full view remains available to permission-authorized editors and
trusted administration jobs, including queued and draft records. Restrict full
view permissions to those readers; it is an editor surface.
Configured public lists scan matching content-type records in database batches, then apply visibility and search before calculating totals and pagination. This includes older published records beyond the legacy search scan cap. Read cost and memory use grow with the collection; cache public results in the host when needed and invalidate that cache after publication.
Within your defineAuthorization() rules, use the server-derived facts.view
to allow the public projection separately from editor access:
rules: ({ cms }) => [
cms.contentType.read.allow(),
cms.record.read.when(({ identity, facts }) =>
identity?.role === "admin" ||
(facts.contentType === "article" && facts.view === "content")
),
// Keep the application's create, update, and delete rules.
]The view fact is present only for publication-filtered content projections on
configured types. An anonymous reader cannot gain editor access by omitting
view under this rule. Related target records retain their own access checks;
allow them separately when exposing public relation reads. Catalog item counts
remain editor reads and are not granted by the content-view rule.
Publication filtering does not replace authorization and does not protect a
previously generated static page. Prefetch with view: "content", then use the
post-publication hook below to refresh the host application's cache or rebuild
its static output. CMS does not start a rebuild or invalidate an external cache.
Adapter-first getters do not have access to the plugin configuration. Their callers must supply the content type's publication policy as the final optional argument when requesting content view; otherwise these trusted low-level helpers retain their unfiltered behavior:
const page = await getAllContentItems(
adapter, "article", { view: "content", limit: 10 }, article.publication,
);Application-owned scheduler
Run the trusted operation from the application's scheduler or a protected job
handler. Authenticate any job endpoint before calling it; CMS deliberately does
not expose a public dispatch route. Request-scoped calls are rejected.
For example, configure a host cron task with * * * * * (once a minute) to invoke
that server handler, using the host's authenticated job mechanism. Keep the
trusted stack and scheduler credentials on the server. Publication happens on
the first successful run after the due instant, so the task frequency determines
the expected delay.
const result = await myStack.trusted.cms.dispatchDueContent({ limit: 20 });
// { scanned, published: [itemId], skipped: [itemId], failures: [...], nextCursor }limit defaults to 20 and accepts integers from 1 through 100. It bounds the
number of due candidates examined per invocation, across configured types.
Candidates are ordered by ID. Continue with { limit: 20, after: result.nextCursor } while nextCursor is non-null to drain a backlog without
an invalid or failed item blocking later candidates. Reset the cursor after a
completed sweep so failed items can be retried on the next scheduled run. Bound
the scheduler's own batches to fit its execution window, and retain the cursor
between invocations if needed. Use returned counts and failures for monitoring.
The server captures the current time when dispatch starts; callers cannot
advance its clock through the operation input.
Dispatch re-reads the current item, schedule, state, and content-type schema
inside the write transaction. Canceled, rescheduled, deleted, or already
published candidates are skipped. Eligible items run normal schema and relation
validation and the update lifecycle, then save the published state, clear
publishAt, and append a revision in the same transaction. Repeated or
concurrent invocations cannot publish the same scheduled version twice.
Production dispatch requires native isolated transactions with
transaction: true;
adapters without that support are rejected with ATOMIC_TRANSACTION_REQUIRED.
The memory adapter is for development: dispatch calls sharing one adapter are
serialized, but arbitrary concurrent editor writes and other processes are not
covered by that serialization.
Each failed item is reported as { id, message, published } and dispatch
continues with the remaining candidates. A pre-commit failure leaves the item
due for a later retry. A post-commit lifecycle or revalidation failure has
published: true: the content and revision already exist and the ID also appears
in published. A later dispatch does not replay post-publication hooks for that
item, so the host must separately retry failed cache invalidations or rebuilds.
Refreshing published output
onAfterPublishContent runs after the publication transaction and the normal
update lifecycle. Use it for the host's cache or rebuild integration:
import { revalidatePath } from "next/cache";
cmsBackendPlugin({
contentTypes: [article],
hooks: {
onAfterPublishContent: async (item) => {
revalidatePath(`/articles/${item.slug}`);
revalidatePath("/articles");
},
},
});Adding this policy needs no additional database columns beyond the revision and
publishAt migration below. Review existing records before opting a type in:
content-view readers immediately hide records that do not satisfy its published
state, and existing due schedules in its scheduled state become eligible on the
next dispatch. Backfill the chosen state field as needed and configure the
scheduler and revalidation integration before relying on scheduled publication.
Database upgrade
Regenerate and apply the database migration from your stack's dbSchema before
serving the updated plugin. The additive schema introduces contentRevision
(with a unique item/version revisionKey and cascading contentItemId reference)
and a nullable contentItem.publishAt date column. It does not rewrite content
payloads, IDs, slugs, or author ownership. Existing items start with empty history;
their first successful post-upgrade write creates version 1. Earlier versions
cannot be reconstructed. The lower-level createCMSContentItem() helper now
also needs the migrated schema and supports publishAt as a Date or null.
API Reference
Backend (@btst/plugin-cms/api)
CMSBackendConfig
Prop
Type
CMSPublicationPolicy
Prop
Type
CMSBackendHooks
Prop
Type
CMSCreateOperationContext
Prop
Type
CMSUpdateOperationContext
Prop
Type
CMSDeleteOperationContext
Prop
Type
Client (@btst/plugin-cms/client)
cmsClientPlugin
Prop
Type
CMSClientConfig
Prop
Type
CMSClientHooks
Customize framework-side data loading, analytics, and error reporting with
lifecycle hooks. The shared CMS operation rules remain the authorization
boundary. onErrorLoad is an observer: exceptions from the callback are
contained and never reject the loader.
Prop
Type
Example usage:
cms: cmsClientPlugin({
hooks: {
beforeLoadDashboard: async (context) => {
await warmDashboardDependencies(context.headers)
},
beforeLoadContentList: async (typeSlug, context) => {
await recordContentListLoad(typeSlug, context.headers)
},
beforeLoadContentEditor: async (typeSlug, id, context) => {
await recordEditorLoad(typeSlug, id, context.headers)
},
onErrorLoad(error, context) {
reportCMSLoaderError(error, context)
},
}
})LoaderContext
Prop
Type
CMSPluginOverrides
Configure CMS-specific overrides and route lifecycle hooks:
Prop
Type
Use classNames in StackProvider.overrides.cms to style built-in UI slots. Classes merge with the defaults; conflicting Tailwind utilities use your override. Omitting a slot preserves its default styling.
overrides={{
cms: {
classNames: { contentTypeCard: "shadow-lg", tableRow: "hover:bg-muted" },
},
}}Schema Converter Utilities (@btst/plugin-cms/client)
The CMS plugin re-exports schema converter utilities for converting between Zod schemas and JSON Schema. These are useful when working with content types programmatically:
zodToFormSchema
Convert a Zod schema to JSON Schema with proper handling for dates, steps metadata, and date constraints:
Prop
Type
Example:
import { zodToFormSchema } from "@btst/plugin-cms/client"
const jsonSchema = zodToFormSchema(ProductSchema, {
steps: [
{ id: "basic", title: "Basic Info" },
{ id: "details", title: "Details" }
],
stepGroupMap: {
name: 0,
price: 0,
description: 1
}
})formSchemaToZod
Convert JSON Schema back to a Zod schema with proper handling for date fields, constraints, and steps metadata:
Prop
Type
Example:
import { formSchemaToZod } from "@btst/plugin-cms/client"
// Convert JSON Schema from database to Zod for validation
const zodSchema = formSchemaToZod(jsonSchema)
const result = zodSchema.safeParse(data)Utility Functions
Prop
Type
Prop
Type
Prop
Type
Types
Prop
Type
Prop
Type
Server-side Data Access
Use the operation surfaces for application business calls:
const types = await myStack.trusted.cms.listContentTypes({})
const items = await myStack.trusted.cms.listContentItems({
typeSlug: "posts",
query: { limit: 10 },
})
await myStack.forRequest(request).operations.cms.createContentItem({
typeSlug: "client-profile",
body: { slug, data },
})forRequest(request).operations.cms enforces authorization. trusted.cms is the explicit trusted surface and still runs validation, authoritative fact derivation, relation planning, transactions, and lifecycle hooks. myStack.raw.cms is reserved for prefetchForRoute.
Standalone getters and createCMSContentItem(adapter, ...) remain lower-level adapter primitives for plugin internals and migrations whose caller intentionally owns validation and lifecycle composition.
Trusted slug and complete relationship reads
getContentItemBySlug(adapter, typeSlug, slug) is a standalone getter, not a
method on myStack.trusted.cms. For a validated trusted server job, filter the
list operation by slug:
const page = await myStack.trusted.cms.listContentItems({
typeSlug: "compound",
query: { slug: "example-compound", view: "content", limit: 1 },
})
const compound = page.items[0] ?? nullUse myStack.forRequest(request).operations.cms instead when the caller must
be authorized. Trusted reads bypass authorization; only expose an explicitly
public projection. view: "content" is not a visibility policy by itself.
Relationship reads return a page, not every matching record. For a complete trusted export or static public page, advance by the actual returned count:
import type { SerializedContentItemContent } from "@btst/plugin-cms/types"
async function allRelatedReferences(compoundId: string) {
const items: Readonly<SerializedContentItemContent<unknown>>[] = []
let offset = 0
while (true) {
const page = await myStack.trusted.cms.listContentByRelation({
typeSlug: "study-reference",
query: { field: "compoundId", targetId: compoundId, view: "content", limit: 100, offset },
})
items.push(...page.items)
offset += page.items.length
if (!page.items.length || offset >= page.total) return items
}
}Choose a limit within the configured maxPageSize. Advancing by returned count
handles short pages, and the empty-page check avoids an endless loop.
Validate each parsedData value against the application's content schema before
using its fields; the generic example leaves that payload as unknown.
Offset pagination is not a snapshot under concurrent
edits; coordinate writes if an export needs a consistent view. Large relationship
costs are tracked separately in #418.
Static Site Generation (SSG)
route.loader() makes HTTP requests to the API resolved by createClientStack(), which silently fails during next build because no dev server is running. Use prefetchForRoute() instead — it reads directly from the database and pre-populates the React Query cache before rendering.
prefetchForRoute(routeKey, queryClient, params?)
| Route key | Params required | Data prefetched |
|---|---|---|
"dashboard" | — | All content types (with item counts) |
"contentList" | { typeSlug: string } | Content types + first page of items |
"newContent" | — | All content types |
"editContent" | { typeSlug: string; id: string } | Content types + specific item |
prefetchForRoute calls ensureSynced(adapter) internally before any DB query. This function is idempotent — concurrent calls during generateStaticParams + generateMetadata + page all share the same Promise and the schema sync runs exactly once.
Next.js example
import { dehydrate, HydrationBoundary } from "@tanstack/react-query"
import { getOrCreateQueryClient } from "@/lib/query-client"
import { getStackClient } from "@/lib/stack-client"
import { myStack } from "@/lib/stack"
import { metaElementsToObject, normalizePath } from "@btst/stack/client"
import type { Metadata } from "next"
// Generate one static page per content type slug
export async function generateStaticParams() {
const types = await myStack.trusted.cms.listContentTypes({})
return types.map((t) => ({ typeSlug: t.slug }))
}
export async function generateMetadata(
{ params }: { params: { typeSlug: string } }
): Promise<Metadata> {
const queryClient = getOrCreateQueryClient()
const stackClient = getStackClient(queryClient)
const route = stackClient.router.getRoute(normalizePath(["cms", params.typeSlug]))
if (!route) return { title: "Content" }
await myStack.raw.cms.prefetchForRoute("contentList", queryClient, { typeSlug: params.typeSlug })
return metaElementsToObject(route.meta?.() ?? []) satisfies Metadata
}
export default async function ContentListPage({ params }: { params: { typeSlug: string } }) {
const queryClient = getOrCreateQueryClient()
const stackClient = getStackClient(queryClient)
const route = stackClient.router.getRoute(normalizePath(["cms", params.typeSlug]))
if (!route) return null
await myStack.raw.cms.prefetchForRoute("contentList", queryClient, { typeSlug: params.typeSlug })
return (
<HydrationBoundary state={dehydrate(queryClient)}>
<route.PageComponent />
</HydrationBoundary>
)
}ISR cache invalidation
If you use Incremental Static Regeneration, call revalidatePath inside the backend lifecycle hooks so Next.js regenerates the page on the next request:
import { revalidatePath } from "next/cache"
import { cmsBackendPlugin } from "@btst/plugin-cms/api"
cmsBackendPlugin({
contentTypes: { ... },
hooks: {
onAfterCreateContent: async (item, context) => {
revalidatePath(`/cms/${context.typeSlug}`, "page")
},
onAfterUpdateContent: async (item, context) => {
revalidatePath(`/cms/${context.typeSlug}`, "page")
},
onAfterDeleteContent: async (id, context) => {
revalidatePath(`/cms/${context.typeSlug}`, "page")
},
},
})Query key consistency
prefetchForRoute uses the same query key shapes as createCMSQueryKeys (the HTTP client). The shared constants live in @btst/plugin-cms/api as CMS_QUERY_KEYS; contentListDiscriminator is exported from @btst/plugin-cms/query-keys, so the two paths can never drift silently.
Shadcn Registry
The CMS plugin UI layer is distributed as a shadcn registry block. Use the registry to eject and fully customize the page components while keeping all data-fetching and API logic from @btst/stack.
The registry installs only the view layer. Hooks and data-fetching continue to come from @btst/plugin-cms/client/hooks.
npx shadcn@latest add https://github.com/better-stack-ai/better-stack/blob/main/packages/stack/registry/btst-cms.jsonpnpx shadcn@latest add https://github.com/better-stack-ai/better-stack/blob/main/packages/stack/registry/btst-cms.jsonbunx shadcn@latest add https://github.com/better-stack-ai/better-stack/blob/main/packages/stack/registry/btst-cms.jsonThis copies the page components into src/components/btst/cms/client/ in your project. All relative imports remain valid and you can edit the files freely — the plugin's data layer stays intact.
Using ejected components
After installing, wire your custom components into the plugin via the pageComponents option in your client plugin config:
import { cmsClientPlugin } from "@btst/plugin-cms/client"
// Import your ejected (and customized) page components
import { DashboardPageComponent } from "@/components/btst/cms/client/components/pages/dashboard-page"
import { ContentListPageComponent } from "@/components/btst/cms/client/components/pages/content-list-page"
cmsClientPlugin({
pageComponents: {
dashboard: DashboardPageComponent, // replaces the CMS dashboard page
// Param routes receive the route context ({ params }) as props
contentList: ({ params }) => (
<ContentListPageComponent typeSlug={params.typeSlug} />
),
// newContent, editContent — omit to keep built-in defaults
},
})Any key you omit falls back to the built-in default, so you can override just the pages you want to change.
AI page tools
The content editor registers fillCmsEntryForm through the optional core page-context provider. With AI Chat page tools enabled, it merges supplied fields into the current draft after validation against the active content type, and can set or clear the publish date. Saving remains explicit. Source plugin version 1.2 and AI Chat version 1.1 or later provide this integration. The source plugin works without AI Chat installed.
Page-scoped presentation
Set overrides.cms.pageOverrides on StackProvider. The supported route keys and
presentation slots are:
| Page key | Slots | Props |
|---|---|---|
dashboard | ContentTypeCard, EmptyState | ContentTypeCardProps, EmptyStateProps |
contentList | EmptyState | EmptyStateProps |
newContent, editContent | EmptyState | EmptyStateProps |
The exported card props contain the serialized content type, item count label,
onOpen callback, and existing card/title class names. Empty states receive the
localized title, optional description, and optional action content.
<StackProvider
stack={stack}
overrides={{
cms: {
pageOverrides: {
dashboard: {
ContentTypeCard: ({ contentType, itemCountLabel, onOpen }) => (
<button type="button" onClick={onOpen}>
{contentType.name}: {itemCountLabel}
</button>
),
},
contentList: {
EmptyState: ({ title, action }) => <section>{title}{action}</section>,
},
},
},
}}
>
{children}
</StackProvider>The dashboard card changes independently from the content list, and new/edit
empty states keep their defaults. Unset slots fall back to the built-in
components; shared field overrides, localization, class names, content forms and
whole-page pageComponents replacements retain their behavior. Reusable
components receive a page override only when explicitly passed a page scope.