--- title: "Documentation" description: "Cmssy developer docs: quickstarts, blocks, rendering in Next.js, Astro and React Router, content and commerce, auth, GraphQL API, CLI and MCP." url: https://www.cmssy.com/docs --- # Documentation Model content and products in cmssy, render them in your own Next.js, Astro or React Router app, and let an agent run the workspace over MCP. ### For you ```bash # npx npx @cmssy/cli@latest init # pnpm pnpm dlx @cmssy/cli@latest init # bunx bunx @cmssy/cli@latest init ``` Adds the SDK to the Next.js, Astro or React Router app in the current folder. [Installation](https://www.cmssy.com/docs/start/installation.md) ### For your agent ```bash claude mcp add --transport http cmssy https://api.cmssy.io/mcp ``` Any MCP client works; Claude Code shown. The server edits content, never your code. [MCP server](https://www.cmssy.com/docs/api/mcp.md) - [Next.js](https://www.cmssy.com/docs/start/installation.md) - [Astro](https://www.cmssy.com/docs/start/installation.md) - [React Router](https://www.cmssy.com/docs/start/installation.md) - [How it works](https://www.cmssy.com/docs/start/how-it-works.md): What lives in cmssy, what lives in your repo, and how a publish reaches the page. - [Your first block, live](https://www.cmssy.com/docs/start/first-block.md): Fresh app, Dev host, a block of your own edited live, deployed, published. - [Block schema & field types](https://www.cmssy.com/docs/blocks/fields.md): Every field builder, options, repeaters and relations in one table. - [MCP server](https://www.cmssy.com/docs/api/mcp.md): Connect Claude, Cursor or any MCP client to the workspace. ## The same docs, as plain text - [llms.txt](https://www.cmssy.com/llms.txt): The index: what cmssy is and where every page lives. - [llms-full.txt](https://www.cmssy.com/llms-full.txt): Every docs page in one file, in tree order. - [Markdown twins](https://www.cmssy.com/docs/start/how-it-works.md.md): Append .md to any docs URL for the page as Markdown. --- title: "Get Started" description: "Install the Cmssy SDK, define your first block, and publish your first page." url: https://www.cmssy.com/docs/start --- # Get Started Install the SDK, define your first block, and publish a page - the fastest path from zero to a live headless site. ## Quickstart Guide Build and ship your first Cmssy page end-to-end in a few minutes. ### 1. Install the SDK Add `@cmssy/next` + `@cmssy/react` to a Next.js (App Router) app and create `cmssy.config.ts`. See [Installation](https://www.cmssy.com/docs/start/installation.md) for the full setup. ### 2. Define a block Create `blocks/hero/block.ts` with `defineBlock` + `fields` and a React component in `blocks/hero/Hero.tsx`, then register it in `cmssy/blocks.ts`. Run `pnpm dev`. ### 3. Create a page in the admin Sign in at [cmssy.io](https://cmssy.io), open your workspace, click **Pages → Add Page**, and give it a name and slug. ### 4. Add your block & edit content Open the page editor - your site is framed for live preview. Drag your **Hero** block onto the canvas and edit its fields in the right panel; changes appear instantly. ### 5. Publish Click **Publish**. Your published content is served from the Cmssy delivery API. ### 6. Live on your site Deploy your Next.js app (e.g. on Vercel) - it renders the published content via `createCmssyPage` (your `app/[[...path]]/page.tsx`). Next, explore the [Blocks](https://www.cmssy.com/docs/blocks.md) guide and the [MCP Server](https://www.cmssy.com/docs/api/mcp.md) for AI-assisted editing. > **TIP: Fastest path** > > Skip the setup - clone [cmssy-io/examples](https://github.com/cmssy-io/examples) and run one of the apps; each points at the public demo workspace, so it renders real content before you have an account. Point it at your own workspace with `npx @cmssy/cli@latest link --token cs_...`. - [Installation](https://www.cmssy.com/docs/start/installation.md): Add @cmssy/next and @cmssy/react to your Next.js app. - [Your first block, live](https://www.cmssy.com/docs/start/first-block.md): One verified path: fresh app, Dev host, a block of your own edited live, deployed, promoted, published. - [Blocks](https://www.cmssy.com/docs/blocks.md): Build reusable blocks with defineBlock + fields. --- title: "How it works" description: "What lives in cmssy, what lives in your repo, and what happens between a request and a rendered page." url: https://www.cmssy.com/docs/start/how-it-works --- # How it works What lives in cmssy, what lives in your repo, and what happens between a request and a rendered page. cmssy stores your content and never renders it. Your app renders your content and never stores it. Everything below follows from that one split. ## What lives where - **In your repo** - block schemas and components. A block is a React component plus a field schema, declared with `defineBlock`. It is code: reviewed, versioned, deployed. - **In cmssy** - pages, block instances and their values, media, models and records, forms. It is data: edited visually or by an AI client, published without a deploy. The line between them does not move. Adding a field means shipping code. Changing a headline does not. ## What a page is A page is a node in a tree. It has a slug derived from its parents, an ordered list of block instances that make up its body, and a layout - header and footer blocks it either owns or inherits from its parent. Every block instance stores its values keyed by language, so `content.en.title` and `content.de.title` are the same field on the same block in two locales. There is no separate translated page. ## From request to rendered page A cmssy frontend needs one route. This is the whole of it: ```tsx // app/[[...path]]/page.tsx import { createCmssyPage } from "@cmssy/next/server"; import { cmssy } from "@/cmssy/config"; import { blocks } from "@/cmssy/blocks"; export const revalidate = 3600; export default createCmssyPage(cmssy, blocks); ``` What happens when a request arrives: 1. The catch-all route receives the path and turns it into a slug. 2. The SDK asks the delivery API for the published page at that slug, plus its layout blocks. No token - published content is public. 3. Each returned block instance carries a `type`. The SDK looks that type up in the registry you passed as the second argument. 4. Your component renders with that instance's content for the active locale. Relation fields arrive already resolved to full records. 5. A block type missing from your registry renders nothing on your site - and a diagnostic card naming the type when you open the editor. A block that throws, in its loader or its render, is contained the same way. Content cannot crash your app. The registry is a plain array you maintain: ```ts // cmssy/blocks.ts import { heroBlock } from "@/blocks/hero/block"; import { pricingBlock } from "@/blocks/pricing/block"; export const blocks = [heroBlock, pricingBlock]; ``` ## The packages The framework is an adapter, never the foundation: - `@cmssy/core` - transport, queries, config, the editor protocol. Zero framework. Runs in Node, on the edge, in a browser, in a cron job. - `@cmssy/react` - rendering: block registry, components, the edit bridge, hooks. - `@cmssy/next` - Next.js bindings only: middleware, route handlers (draft, revalidate, block data) and page factories. `Metadata`, the sitemap and robots are your app's own routes - see [SEO](https://www.cmssy.com/docs/rendering/seo.md). Adapters for other frameworks sit beside `next`, not on top of it, so an Astro or Remix app never installs React just to fetch a page. `@cmssy/next` splits by runtime and the entries do not mix: `@cmssy/next/middleware` runs on the edge, `/server` in RSC and route handlers, and the root entry holds config and helpers safe to import anywhere. ## Editing Two ways in, one set of content. The **visual editor** loads your real site in a frame and talks to it over `postMessage`. You edit the actual components, not a preview approximation - which is why the edit bridge lives in `core` rather than in the React package. The **MCP server** gives an AI client the same write access: create pages, edit block content, upload media, publish. It edits content, never your code. ## Drafts and publishing Edits land in a draft. The public delivery API only ever returns published content, so an unfinished page is invisible to your site by construction - not by a filter you have to remember to apply. To see drafts while developing, append `?cmssyDev=1` to any URL. It requires `CMSSY_API_TOKEN` and renders your own draft overlay; without the flag you get published content. Publishing does not deploy. Your app caches pages according to its own `revalidate` value, and cmssy can call a revalidation webhook on publish to invalidate them sooner. ## Next steps - [Installation](https://www.cmssy.com/docs/start/installation.md) - add the SDK to an existing Next.js app. - [Quickstart](https://www.cmssy.com/docs/start/quickstart.md) - first block and first page, end to end. - [Block development](https://www.cmssy.com/docs/blocks/define.md) - `defineBlock` and the field schema in depth. - [API & AI](https://www.cmssy.com/docs/api.md) - the delivery API and the MCP server. --- title: "Quickstart" description: "Get started with Cmssy in minutes. Create your workspace, add pages, customize blocks, and publish your first website." url: https://www.cmssy.com/docs/start/quickstart --- # Quickstart > **TIP: Start from a runnable example** > > Want a head start? Clone [cmssy-io/examples](https://github.com/cmssy-io/examples) - standalone apps for Next.js (`simple-blog`, `next-storefront`), Astro and React Router, each with an `.env.example` pointing at the public demo workspace, so a fresh clone renders real content before you have an account. Point one at your own workspace with `npx @cmssy/cli@latest link --token cs_...`. ## Quickstart From an empty workspace to a content API your app reads - the same five steps the setup card on your workspace home tracks for you. ### 1. Model your content A model is a content type your API serves. Open **Models**, create one and add its fields. Set **Delivery access** to *public* - models are private by default, so your app cannot read one until you do. Or press `Cmd` + `K` and let [Spotlight](https://www.cmssy.com/docs/editor/assistant.md) build it from one sentence. See [Data models](https://www.cmssy.com/docs/content/data-models.md). ### 2. Add content Add a record by hand under the model, or import a spreadsheet - Spotlight turns the columns into a model and loads the rows for you. A few records are enough to see the API respond. ### 3. Run your first query The setup card runs a delivery query against your records, exactly as your app will - anonymous, over the public endpoint. Copy it as curl or open it in the playground. A refused query means the model is still private. See [GraphQL delivery API](https://www.cmssy.com/docs/api/graphql.md). ### 4. Connect your app Scaffold an app with your framework's own CLI, then let the cmssy CLI wire it and link it to this workspace: ``` npx create-next-app@latest my-site && cd my-site npx @cmssy/cli@latest init npx @cmssy/cli@latest link --token cs_... ``` `init` writes the config, the block registry with an example block, the catch-all page and the editor and draft routes. `link` fills `.env.local` with the workspace slugs and draft secret, pushes your block manifest and checks the wiring. The token comes from **Create token** on the setup card or from [API tokens](https://www.cmssy.com/docs/auth/api-tokens.md). Astro and React Router work the same way - see [CLI](https://www.cmssy.com/docs/api/cli.md). ### 5. Publish Run `pnpm dev`, open a page in the editor and enable the **Dev host** with your local URL - the editor frames your app for live preview without touching the shared preview URL. Create a page (or ask Spotlight for a homepage), drop in your block and click **Publish**. Published content is served from the delivery API and your app renders it through the catch-all route. Next: [Blocks](https://www.cmssy.com/docs/blocks.md), [Draft preview](https://www.cmssy.com/docs/rendering/draft-preview.md), [MCP server](https://www.cmssy.com/docs/api/mcp.md). --- title: "Installation" url: https://www.cmssy.com/docs/start/installation last_updated: 2026-09-20 --- # Installation > **TIP: Start from a runnable example** > > Want a head start? Clone [cmssy-io/examples](https://github.com/cmssy-io/examples) - standalone apps for Next.js (`simple-blog`, `next-storefront`), Astro and React Router, each with an `.env.example` pointing at the public demo workspace, so a fresh clone renders real content before you have an account. Point one at your own workspace with `npx @cmssy/cli@latest link --token cs_...`. Wire cmssy into a Next.js, Astro or React Router app with one command, connect it to your workspace and open it in the editor. ## Prerequisites - **Node.js** - Node 22 or newer. The SDK itself needs at least Node 20, but current Astro and React Router releases need 22, and cmssy is tested on 22. We recommend [nvm](https://github.com/nvm-sh/nvm) - **pnpm** - npm, yarn and bun work too; the CLI prints the install command that matches your lockfile - **A cmssy workspace and an API token** - create the token under **API tokens** in the dashboard sidebar; it is what connects the app to the workspace - **A Next.js (App Router), Astro or React Router 7 app**, new or existing. The steps are the same; the commands and the files init writes differ, and are in the tabs below. ## Create the app and wire cmssy Scaffold an app (or `cd` into the one you have), then let the CLI wire it. `cmssy init` detects the framework, copies the wiring files into your repo, adds the framework's adapter (`@cmssy/next`, `@cmssy/astro` or `@cmssy/remix`) with `@cmssy/react` and `@cmssy/core` to `package.json`, and prints every file it wrote with a line on what it is for. Every file is plain code in your repository - open it, change it, there is no hidden runtime behind it. Files that already exist are skipped and listed; `--force` overwrites them. When the app lints and has no config of its own, init also drops an `eslint.config.mjs` with the cmssy plugin. The full description of each file is on the [CLI](https://www.cmssy.com/docs/api/cli.md) page. Pick your framework - the choice carries over to the other tabbed examples in the docs. ### Next.js ```bash npx create-next-app@latest my-site # App Router: yes cd my-site npx @cmssy/cli@latest init pnpm install ``` Under `src/` when the app uses one. **What init writes** | File | What it does | | - | - | | `cmssy.config.ts` | Reads server env and validates it at startup. Server-only: never import a value from it in a client component. | | `proxy.ts` | Resolves the language, rewrites verified editor traffic to `/cmssy-edit`, applies the CSP that lets the admin frame the site. | | `services/pages.ts` | Your delivery queries, in your repo. `generateStaticParams` lives here. | | `cmssy/blocks.ts` | The block registry - the server renders from this list, the editor loads it lazily. | | `cmssy/editor.tsx`, `cmssy/editable-layout.tsx`, `cmssy/site-providers.tsx` | Editor bootstrap, header and footer through the edit bridge, and the one place your own providers go. | | `blocks/hero/` | An example block: the schema beside the component that reads it. | | `app/[[...path]]/`, `app/cmssy-edit/[[...path]]/` | Page and layout for the site and for the framed editor. These are the root layouts, so the app has no `app/layout.tsx`. | | `app/api/draft/route.ts`, `app/api/revalidate/route.ts` | Draft-mode entry for the editor, and the on-publish revalidation webhook. | | `.env.example` | The variables the config reads. | **Run and deploy** `pnpm dev` serves . Deploy like any Next.js app - `vercel`, or a push to the Git repo your host watches. Pages are static with ISR, so point a `content.changed` webhook at `https://your-site.com/api/revalidate` and set `CMSSY_WEBHOOK_SECRET` in the host: a publish then shows up without a redeploy. ### Astro ```bash npm create astro@latest my-site cd my-site npx astro add react node npx @cmssy/cli@latest init rm src/pages/index.astro pnpm install ``` `astro add react node` adds the React integration and the Node server adapter: blocks are React components rendered on the server, and the edit route needs a server. Delete `src/pages/index.astro` - it shadows the cmssy catch-all for `/`. init reminds you of both. **What init writes** | File | What it does | | - | - | | `src/cmssy.config.ts` | Reads env and validates it at startup. In dev it also loads `.env.local`, which Astro does not put in `process.env` itself. | | `src/middleware.ts` | The whole adapter: resolves the language, rewrites verified editor requests to `/cmssy-edit`, applies the CSP that lets the admin frame the site. | | `src/cmssy/blocks.ts` | Every block the app renders. | | `src/cmssy/editor.tsx` | The edit bridge, as a client island. | | `src/cmssy/layout-slot.tsx` | Header and footer: server-rendered for visitors, through the edit bridge on the edit route. | | `src/cmssy/hero.tsx` | An example block: the schema beside the component that reads it. | | `src/components/Blocks.tsx` | Renders React blocks on the server with no client JS - the visitor gets HTML. | | `src/pages/[...path].astro` | The public catch-all. Its `blocks` prop is what lets the editor fill the header and footer. | | `src/pages/cmssy-edit/[...path].astro` | Where the editor iframe lands. It must stay dynamic: a prerendered page never sees the query string. | | `.env.example` | The variables the config reads. | **Run and deploy** `pnpm dev` serves . Deploy it as a Node server: `pnpm build`, then `node ./dist/server/entry.mjs`. Pages render on each request, so a publish shows up on the next one - no webhook. Set the `CMSSY_*` variables in the host: `.env.local` is read in dev only. ### React Router ```bash npx create-react-router@latest my-site cd my-site npx @cmssy/cli@latest init --force rm app/routes/home.tsx pnpm install ``` The template ships its own `app/root.tsx` and `app/routes.ts`, and cmssy needs both: `routes.ts` mounts the cmssy page for `/` and every other path, `root.tsx` sets `` from the page's language. On a fresh app `--force` is safe; on an existing one run init without it and merge the two files by hand - init prints what to add. Then delete `app/routes/home.tsx`, which nothing routes to any more, and add `import "./app.css";` back to `app/root.tsx` if you want the template's styles. **What init writes** | File | What it does | | - | - | | `cmssy.config.ts` | Reads env and validates it at startup. | | `app/root.tsx` | The root layout. `` comes from `useCmssyLocale()`, so a prefixed URL declares the language it renders. | | `app/routes.ts` | Mounts the page module twice: the splat does not match `/`, so the homepage needs its own entry. | | `app/cmssy/blocks.ts` | Every block the app renders. | | `app/cmssy/editor.tsx` | The edit bridge. | | `app/cmssy/layout-slot.tsx` | Header and footer: server-rendered for visitors, through the edit bridge for the editor. | | `app/cmssy/hero.tsx` | An example block: the schema beside the component that reads it. | | `app/routes/page.tsx` | One route for both modes - a React Router page always sees its query string, so there is no separate edit route. Its headers are what let the admin frame the site. | | `.env.example` | The variables the config reads. | **Run and deploy** `pnpm dev` serves . Deploy it as a Node server: `pnpm build`, then `pnpm start`. Pages render on each request, so a publish shows up on the next one - no webhook. `pnpm start` does not read `.env.local`: set the `CMSSY_*` variables in the environment the server runs in. ## Connect the app to your workspace `cmssy link` writes `CMSSY_ORG_SLUG`, `CMSSY_WORKSPACE_SLUG` and `CMSSY_DRAFT_SECRET` into `.env.local` and verifies them against the API, so a typo fails here and not on the first render. ```bash npx @cmssy/cli@latest link --token cs_... ``` Without `--token` the CLI reads `CMSSY_API_TOKEN`. A token from a user with several workspaces gets asked which one; `--workspace ` skips the question. ## The environment, in one place | Variable | What it is | Where it comes from | | - | - | - | | `CMSSY_ORG_SLUG` | Your organization slug | `cmssy link` (Settings → Headless) | | `CMSSY_WORKSPACE_SLUG` | Your workspace slug - resolves the workspace | `cmssy link` (Settings → Headless) | | `CMSSY_DRAFT_SECRET` | Secret the editor proves itself with to enter draft / preview mode | `cmssy link` (Settings → Headless) | | `CMSSY_WEBHOOK_SECRET` | Signing secret of the `content.changed` webhook pointed at `/api/revalidate` | Settings → Webhooks - Next.js only, on the deployed site. Astro and React Router render per request and need no webhook | | `CMSSY_API_URL` | The cmssy API's GraphQL endpoint. Defaults to `https://api.cmssy.io/graphql` | Self-host / staging only | | `CMSSY_EDITOR_ORIGIN` | Admin origin that frames your site. Defaults to `https://www.cmssy.io` | Self-host only | `cmssy.config.ts` passes them to `defineCmssyConfig` raw - imported from your adapter: `@cmssy/next` below, `@cmssy/astro` or `@cmssy/remix` otherwise. It validates at startup and names any variable you are missing - a `?? ""` fallback would hide that, and the error would surface later, somewhere unrelated. ```typescript import { defineCmssyConfig } from "@cmssy/next"; export const cmssy = defineCmssyConfig({ org: process.env.CMSSY_ORG_SLUG, workspaceSlug: process.env.CMSSY_WORKSPACE_SLUG, draftSecret: process.env.CMSSY_DRAFT_SECRET, }); ``` Keep `.env.local` out of version control. In production, set the same variables in your hosting provider (e.g. the Vercel project settings). ## Start development ```bash pnpm dev ``` The dev server comes up on for Next.js, [:4321](http://localhost:4321) for Astro and [:5173](http://localhost:5173) for React Router. It renders the published pages of your workspace with the blocks in `cmssy/blocks.ts`. ## Editor preview The editor frames your site in an iframe and edits it live. The draft entry and the CSP that lets the admin frame the site are already in place from init; what you point at your site is one setting: - While developing, enable the **Dev host** in the editor with your dev server's URL, e.g. `http://localhost:3000`. That target is yours only and touches nothing shared. - For the deployed site, set the workspace **Preview URL** (Settings → Headless) - e.g. `https://your-site.com`. On cmssy cloud the editor origin is configured for you. If you self-host the admin, set `CMSSY_EDITOR_ORIGIN` to your admin origin - the SDK uses it for the postMessage bridge and for the CSP `frame-ancestors` that lets the admin frame your site. ## Deploy Set the same environment variables in your host and set the workspace **Preview URL** (Settings → Headless) to the deployed site. The build and start commands, and whether a publish needs a webhook, depend on the framework - see **Run and deploy** in your framework's tab above. ## Updating the SDK Bump the `@cmssy/*` packages **together** - the adapter (`@cmssy/next`, `@cmssy/astro` or `@cmssy/remix`) peer-depends on a matching `@cmssy/react` and `@cmssy/core`. The CLI is not installed; `npx @cmssy/cli@latest` always runs the current one. If you add `@cmssy/cli` as a devDependency instead, it depends on `esbuild`, which has a postinstall script. pnpm 10+ skips that script until you approve it, and the first `pnpm exec cmssy` then fails with `ERR_PNPM_IGNORED_BUILDS`. Allow it in `pnpm-workspace.yaml`: ```yaml allowBuilds: esbuild: true ``` ```bash pnpm up "@cmssy/*" pnpm why @cmssy/react # check the installed version ``` ## Wiring by hand `init` is a file copier, nothing more. If you would rather add the files yourself, or want to read what each one does before trusting it, the per-framework layout is described under [Rendering](https://www.cmssy.com/docs/rendering.md) and the [CLI](https://www.cmssy.com/docs/api/cli.md) page lists every file init writes, for Next.js, Astro and React Router. ## Troubleshooting - **init says a file exists, skipped** - the app already had it (usually `proxy.ts`, a root layout or React Router's `app/routes.ts`). init never overwrites without `--force`; diff yours against the file init would write and merge by hand. - **link: "no API token given"** - pass `--token cs_...` or set `CMSSY_API_TOKEN`. The token comes from **API tokens** in the dashboard sidebar. - **"Preview didn't connect"** - the Dev host or the workspace Preview URL must point at the running site. If you self-host the admin, `CMSSY_EDITOR_ORIGIN` must be your admin origin. - **Blank page** - `CMSSY_WORKSPACE_SLUG` must match your workspace (and, if self-hosting, `CMSSY_API_URL` must be the *full* GraphQL endpoint). - **"Port already in use"** - stop other dev servers or start on another port (`next dev -p 3001`, `astro dev --port 4322`, `react-router dev --port 5174`) and point the Dev host at it. - **Node.js version error** - the SDK needs Node 20 or newer and current frameworks need 22; switch to Node 22 (`nvm install 22`). ## Next steps - [Your first block, live](https://www.cmssy.com/docs/start/first-block.md) - from this setup to a block you wrote, edited in the editor and published - [Block Development](https://www.cmssy.com/docs/blocks/define.md) - block anatomy, schemas and field types - [Page Builder](https://www.cmssy.com/docs/editor/page-builder.md) - editing content in the visual editor --- title: "First block" description: "One path, end to end: install the SDK, connect the workspace, frame your local app in the editor with Dev host, write a block, edit it live, deploy, promote, publish and wire the revalidate webhook." url: https://www.cmssy.com/docs/start/first-block last_updated: 2026-09-20 --- # First block > **INFO: What you need before you start** > > Node 22 or newer (cmssy is tested on 22), a package manager (the examples use `pnpm`, `npm` works the same), a cmssy workspace and one API token. Create the token on the setup card of your workspace home or under **Settings → API Tokens**; it starts with `cs_`. Forty minutes end to end, most of it reading. Deploying (step 7) needs any host that runs Next.js; the walkthrough was verified with a tunnel standing in for the deploy. One path, no detours: a fresh Next.js app, the cmssy wiring, your local site framed in the editor, a block you wrote edited in place, then deployed, promoted, published - and a webhook so a publish shows up now, not after the cache expires. Every step below was run end to end on 2026-09-20 with @cmssy/cli 16.11.0 and Next.js 16.3. The other pages in this section explain each piece on its own. This one walks the whole path in order, with the exact commands and the exact labels you will see. At the end you have a Next.js site that renders your workspace, a block of your own on a published page, and a workspace that tells your site when to refresh. ## 1. Create the app and wire cmssy Start from your framework's own generator, then let the cmssy CLI add the wiring. It detects Next.js from `package.json`. Always call the CLI as `@cmssy/cli@latest`: a stale global install would otherwise win and fail with *Cannot query field "myWorkspaces"*. ```bash npx create-next-app@latest my-site # App Router: yes cd my-site npx @cmssy/cli@latest init pnpm install ``` `init` writes 16 files and never overwrites without `--force`: - `cmssy.config.ts` - reads `CMSSY_ORG_SLUG`, `CMSSY_WORKSPACE_SLUG` and `CMSSY_DRAFT_SECRET` straight from `process.env`, so a missing variable fails at startup with its name instead of somewhere unrelated later. `.env.example` lists them; `link` fills the real `.env.local` in the next step. - `proxy.ts` - the middleware preset: locale prefixes, the verified edit-mode rewrite, and the CSP that lets only the cmssy admin frame your site. - `cmssy/blocks.ts` - the block registry, with an example `hero` block in `blocks/hero/`. Next to it: `cmssy/editor.tsx` (loads the registry lazily on the client), `cmssy/editable-layout.tsx` (header and footer through the edit bridge) and `cmssy/site-providers.tsx` (the one place your own providers go). - `app/[[...path]]/page.tsx` and `layout.tsx` - the public catch-all that renders every cmssy page, plus `services/pages.ts` it reads from. Your generator's `app/page.tsx` and `app/layout.tsx` move to `.cmssy-backup/`. - `app/cmssy-edit/[[...path]]/` - the route the editor is rewritten to, with its own root layout; both layouts import `globals.css`, so keep them in step when you add CSS or metadata. - `app/api/draft/route.ts` and `app/api/revalidate/route.ts` - draft preview and the publish webhook you will wire in step 8. `init` also wires `@cmssy/eslint-plugin` into `eslint.config.mjs` and adds `@cmssy/next`, `@cmssy/react`, `@cmssy/core` and the plugin to `package.json` at its own version - that is why the install comes after it. ## 2. Connect the app to your workspace ```bash npx @cmssy/cli@latest link --token cs_... ``` `link` fetches the organization and workspace slugs and the draft secret with your token, writes the three into `.env.local`, checks that the workspace answers, that the secret matches and that `/api/draft` is mounted, and prints the editor deep link for this workspace. If the workspace has no block manifest yet it also pushes one from your registry, so the editor palette knows your blocks before the first deploy. If your token can see several workspaces it asks which one - in a non-interactive shell it stops instead, so pass `--workspace `. The output ends with draft-preview links that embed the secret: do not paste them anywhere public. Prefer `link` to copying by hand. If you do copy, every value is under **Settings → Headless**: **Organization**, **Workspace**, and **Draft preview secret** with its **Copy** button. **Regenerate** invalidates the old secret immediately - update `.env.local` when you use it. ## 3. The environment, in one place | Variable | Set by | What it does | | - | - | - | | `CMSSY_ORG_SLUG` | `link` | Organization slug. Required. | | `CMSSY_WORKSPACE_SLUG` | `link` | Workspace slug. Required. | | `CMSSY_DRAFT_SECRET` | `link` | Server-only. Gates draft preview and edit mode: the editor sends it, `proxy.ts` verifies it. Required. | | `CMSSY_WEBHOOK_SECRET` | you, step 8 | Signing secret of the `content.changed` webhook that hits `/api/revalidate`. Without it the route answers 500. | | `CMSSY_API_TOKEN` | optional | Lets you omit `--token` on CLI commands. Never needed by the running site. | | `NEXT_PUBLIC_SITE_URL` | optional | Your own public origin, if you build canonical URLs, hreflang or a sitemap like the starter does. cmssy stores canonical content and never your domain. | Keep the same names in your host's environment when you deploy (step 7). Do not add `?? ""` fallbacks: an empty slug is a silent 404, a named missing variable is a fix. ## 4. Run it and frame it in the editor ```bash pnpm dev # http://localhost:3000 ``` On its own, `localhost:3000` renders *published* content - a fresh workspace shows the starter's *Nothing published yet at /* page, and that is correct. The live editing happens in the cmssy editor, which frames your running app: 1. Open the editor link that `link` printed (or **Pages** in the dashboard) and open a page - create one if the workspace is empty. 2. In the editor header click **Dev host**. Turn on **Enable dev host**, enter `http://localhost:3000` under **Local dev host** and click **Apply**. If the page has unsaved changes you are asked to confirm **Enter dev preview?**. A blue banner appears: *Dev preview - changes save to your isolated dev buffer, not production.* The canvas now shows your local app, and the block palette (**Add block**, or the **Blocks** tab in the left panel) lists whatever `cmssy/blocks.ts` exports - just **Hero** for now. The editor reads the schemas from the framed site itself on every handshake. Three things to know about Dev host: - It accepts localhost URLs only (`localhost`, `127.0.0.1`, `::1`, `*.localhost`), http or https. Chrome frames plain http from the https editor; Firefox and Safari may block it, use a tunnel there. - It is yours alone. The URL lives in your browser session and the on/off switch is per user. The team keeps using the saved **Preview URL** (Settings → Headless), which Dev host does not touch. - While it is on, edits go to **your dev buffer**, not to the shared page draft, and **Publish** is disabled. Step 7 moves the buffer into the real draft. Reloading the editor is fine: the framed site loads the shared draft, and the editor puts your buffered blocks back on the canvas as soon as the site reports in. ## 5. Write a block Let the CLI scaffold it; the name must be kebab-case: ```bash npx @cmssy/cli@latest add block feature-card ``` This creates two files and registers the block in `cmssy/blocks.ts` for you: ```typescript // blocks/feature-card/FeatureCard.tsx import { fields, type BlockProps } from "@cmssy/react"; export const featureCardProps = { heading: fields.text({ label: "Heading", required: true }), text: fields.textarea({ label: "Text" }), }; export default function FeatureCard({ content, }: BlockProps) { return (

{content.heading}

{content.text ?

{content.text}

: null}
); } ``` ```typescript // blocks/feature-card/block.ts import { defineBlock } from "@cmssy/react"; import FeatureCard, { featureCardProps } from "./FeatureCard"; export const featureCardBlock = defineBlock({ type: "feature-card", label: "Feature card", component: FeatureCard, props: featureCardProps, }); ``` The schema is the only place a field is named: `BlockProps` types `content` from it, so renaming `heading` is a compile error rather than an empty card. Give the scaffold some shape before you go back to the editor - it ships unstyled, and an empty `

` is zero pixels tall, so you would see nothing until you type: ```typescript

{content.heading}

{content.text ?

{content.text}

: null}
``` No restart is needed: hot reload reloads the framed page and the editor re-reads the schemas - **Feature Card** shows up in the palette within a few seconds. If it does not, reload the editor page once. Everything else about fields, loaders and layout blocks is in [Block Development Guide](https://www.cmssy.com/docs/blocks/define.md). ## 6. Put it on the page and edit it live Back in the editor (Dev host still on): drag **Feature Card** from the palette onto the canvas, fill **Heading** and **Text** in the properties panel and watch the section update in your app as you type. Change the component's markup in your code editor and the canvas follows on hot reload. No warning appears for the new block: the editor counts a type the framed site declares as known, even though the workspace's block manifest only learns it in step 7. If a yellow notice does list a type, the running site really does not render that block - restore the block in code or remove it from the page. Click **Save page**. The toast says *Saved to your dev buffer*: this is your personal working copy, so a block that does not exist in the deployed site yet cannot break anybody's preview. ## 7. Ship the block, promote, publish Three things have to know about `feature-card` before its content can go public: the deployed site (so visitors can render it), the shared editor preview (which frames the saved **Preview URL**), and the workspace's **block manifest** (which **Promote to draft** validates against). In that order: 1. **Deploy the app** (for example `vercel`, or push to the connected repository) with the same variables from step 3 set in the host's environment. 2. **Point the Preview URL at the deployment** - Settings → Headless → **Preview URL**, or `npx @cmssy/cli@latest link --token cs_... --preview-url https://my-site.vercel.app`. 3. **Update the block manifest** from the code you just deployed: `npx @cmssy/cli@latest sync-manifest --token cs_...`. It prints exactly what changes (here: *adds feature-card*) and activates the new manifest. Alternative without the CLI: turn Dev host off once - the editor reads the deployed site's blocks and, because this change only adds a type, activates it on its own; a change that removes or reshapes types is only *proposed* and waits for review under Settings → Headless → Block manifest. 4. Back in the editor with Dev host on, click **Promote to draft** in the blue banner. Your dev buffer becomes the page's real draft. Skipping item 3 gets you a toast naming the missing type - *Block type feature-card is not in the workspace block manifest yet* - with the same two ways out. 5. Turn Dev host off (**Dev host** → switch off; confirm **Exit dev preview?** if asked). The canvas now frames the deployed site and renders your block there. 6. Click **Publish**. Publishing does not deploy anything - the block already shipped in item 1; publishing only flips the content to public. ## 8. Make a publish show up now: the revalidate webhook The catch-all route generated by `init` caches: `export const revalidate = 3600`. Without help, a page you publish keeps serving the old copy for up to an hour. cmssy closes that gap by calling your site on every publish - you only have to register the endpoint. 1. In the dashboard open **Settings → Webhooks** and click **Add endpoint**. 2. URL: `https://your-site.com/api/revalidate`. Events: **content.changed** (one event that fires for every page, record, media and settings change; you do not need the granular ones for cache purposes). 3. **Copy the secret now** - it is shown once. Set it as `CMSSY_WEBHOOK_SECRET` in your host's environment and redeploy. What happens on publish: cmssy signs the payload with HMAC-SHA256 over `timestamp.body` and sends it with the `x-cmssy-signature: t=…,v1=…` header. `createCmssyRevalidateRoute` in `app/api/revalidate/route.ts` verifies the signature against your secret and expires the cmssy content cache tags, so the next request renders fresh content. **Recent deliveries** on the same settings page shows each call and its response; **Rotate secret** is there when you need a new one - the old one stops working immediately, so update the environment in the same move. To try it before you deploy, expose the dev server with a tunnel (`cloudflared tunnel --url http://localhost:3000` or ngrok), register the tunnel URL as the endpoint, put the secret in `.env.local` and restart `pnpm dev` (env changes are not hot-reloaded). A publish then shows up as *POST /api/revalidate 200* in the terminal and as a *success* row under Recent deliveries. ## 9. If something does not line up - **The block is not in the palette.** Is Dev host on and pointing at the port your app runs on? Is the block in the `blocks` array of `cmssy/blocks.ts`? Reload the editor page once. - **The block is in the layers list but the canvas shows nothing.** The block is empty or unpadded (an empty heading has no height) or hidden under the yellow notice - type a heading, dismiss the notice, add padding. - **The canvas shows published content instead of edit mode.** The draft secret the editor sent does not match your `CMSSY_DRAFT_SECRET` - run `link` again. An unverified edit request deliberately renders the public site. - **Promote to draft says a block type is not in the workspace block manifest yet.** The manifest predates your block. Run `sync-manifest` from the deployed code, or turn Dev host off once with the Preview URL pointing at a deployment that has the block, then promote again. - **Publish is greyed out.** You are in dev preview. **Promote to draft**, exit Dev host, publish. - **Published, but the site shows the old page.** Check **Recent deliveries** under Settings → Webhooks. A 500 means `CMSSY_WEBHOOK_SECRET` is missing on the host; a 401 means it does not match; no delivery at all means the endpoint is not subscribed to `content.changed`. - **`link` says the workspace has a manifest already.** Expected after the first run. `sync-manifest` replaces it when you want the palette to match a registry you changed without opening the editor. - **`npx @cmssy/cli` fails with "Cannot query field myWorkspaces".** An old global `@cmssy/cli` answered instead of the current one. Use `npx @cmssy/cli@latest` or remove the global install. ## Next - [Schema & field types](https://www.cmssy.com/docs/blocks/fields.md) - every field, repeaters, conditional fields. - [Server loaders](https://www.cmssy.com/docs/blocks/loaders.md) - fetching during SSR without shipping the client the query. - [Draft preview](https://www.cmssy.com/docs/rendering/draft-preview.md) - the three ways to see unpublished content and why `?cmssyEdit=1` alone does nothing. - [Webhooks](https://www.cmssy.com/docs/api/webhooks.md) - all events and the signature in detail. - [CLI](https://www.cmssy.com/docs/api/cli.md) - `init`, `link`, `add block`, `sync-manifest`. --- title: "Environment" description: "The three required cmssy values, the optional ones, and the variables your own app owns - with which are server-only and which reach the browser." url: https://www.cmssy.com/docs/start/env --- # Environment Three required values, a few optional ones, and the variables that are yours rather than the CMS's. A cmssy app reads two kinds of value: what the workspace gives you, and what your own app decides. Keeping them apart is the whole of this page. ## Required Copy these from **Settings → Headless** in the dashboard, or let `npx @cmssy/cli@latest link` write them into `.env.local` for you. | Variable | What it is | | - | - | | `CMSSY_ORG_SLUG` | Your organization slug. It sits in the delivery path, which is why a workspace slug only has to be unique within its org. | | `CMSSY_WORKSPACE_SLUG` | The workspace whose content this app renders. | | `CMSSY_DRAFT_SECRET` | Guards draft preview and edit mode. Generated per workspace - not a string you invent. | Pass them to `defineCmssyConfig` **raw**. A `?? ""` fallback turns a missing variable into an empty one, and the failure then surfaces somewhere unrelated. ## Optional, and when you need them | Variable | When | | - | - | | `CMSSY_API_TOKEN` | A `cs_` token. Required for the `?cmssyDev=1` dev-draft overlay, and read by `cmssy link`. Development only - leaving it set does not change what visitors see. | | `CMSSY_API_URL` | The cmssy API's GraphQL endpoint, `https://api.cmssy.io/graphql` by default. The SDK derives your workspace's delivery URL (`/public/{org}/{workspace}/graphql`) from it and the CLI sends its admin queries to it, so keep the `/graphql` path. Set it only for self-hosting or a staging backend. The local MCP server reads a variable of the same name as an origin, without `/graphql` - see [MCP server](https://www.cmssy.com/docs/api/mcp.md). | | `CMSSY_EDITOR_ORIGIN` | The admin origin allowed to frame your site. Defaults to cmssy cloud; set it only if you self-host the admin, because it drives both the postMessage bridge and the CSP `frame-ancestors`. | ## Yours, not the CMS's These are not cmssy settings. cmssy stores canonical content and never your domain, your analytics IDs or your route secrets. | Variable | What it is | | - | - | | `CMSSY_WEBHOOK_SECRET` | Signs the `content.changed` webhook that hits your `/api/revalidate` route. cmssy generates it when you create the webhook under Settings → Webhooks - copy it here. See [webhooks](https://www.cmssy.com/docs/api/webhooks.md). | | `NEXT_PUBLIC_SITE_URL` | Your public origin. Canonical URLs, hreflang alternates and the sitemap are built from it. | | `NEXT_PUBLIC_GA_ID`, `NEXT_PUBLIC_GTM_ID` | Analytics and tag manager. Guard on them so preview deployments and local runs stay out of your numbers - see [scripts](https://www.cmssy.com/docs/rendering/scripts.md). | ## Server-only means server-only Every `CMSSY_*` variable above is server-side. Next only ships `NEXT_PUBLIC_*` to the browser, so a client component that reads the config does not get a misconfigured value - it gets a missing one. That is the failure people meet: `defineCmssyConfig` throwing about missing variables when the variables are set correctly. The cause is an import, not the environment - a `"use client"` component pulled a *value* out of a module that reads the config. Types are fine, they are erased. Values drag `process.env` into the bundle. Keep secrets out of version control, and set the same variables in your host (Vercel project settings, or equivalent) for production. ## Next steps - [Installation](https://www.cmssy.com/docs/start/installation.md) - where these first get used. - [Draft preview](https://www.cmssy.com/docs/rendering/draft-preview.md) - what the draft secret and the API token actually give access to. - [CLI](https://www.cmssy.com/docs/api/cli.md) - `cmssy link` writes the required three and verifies them. --- title: "Blocks" description: "Learn cmssy's headless block architecture - defineBlock, fields schema, block instances, the React component, and locale context with @cmssy/react." url: https://www.cmssy.com/docs/blocks last_updated: 2026-06-29 --- # Blocks How blocks work in the headless model - defineBlock, instances, the component, context, and the data loader. ## Overview Blocks are the building units of every Cmssy page. In the headless model a block is a **React component in your own Next.js repo**, declared with `defineBlock` and a `fields` schema. The Cmssy admin lets editors place and configure block instances; your site renders them with the SDK. A block has three parts: - **Schema** (`fields`) - the editable fields shown in the admin - **Component** - the React component that renders the content - **Registration** - the block added to your `cmssy/blocks.ts` array *** ## Defining a block A block is declared with `defineBlock` and a `fields` schema, and its component derives its props from that same schema with `BlockProps` - so a field is named in exactly one place. [Block development](https://www.cmssy.com/docs/blocks/define.md) walks through it end to end; [Schema & field types](https://www.cmssy.com/docs/blocks/fields.md) lists every field type. *** ## Block instances When an editor adds your block to a page, Cmssy stores a block instance: ```typescript { id: string; // unique UUID for this instance type: string; // matches your block's `type` (e.g. "hero") content: Record; // language-keyed field values } ``` Content is stored per language (`{ en: {...}, pl: {...} }`); the SDK resolves the active locale before passing `content` to your component, so you read fields directly. *** ## The component, context & data Your component receives `{ content, context, data }`. `content` is already resolved for the active locale and typed from your schema; `context` carries `locale` and `isPreview`, plus `forms`, and `auth` / `workspace` when your app supplies them through `buildBlockContext`; `data` is whatever a [server loader](https://www.cmssy.com/docs/blocks/loaders.md) returned. Registration is one array, `cmssy/blocks.ts`, and it is the single source of truth: it drives rendering, and the editor learns each block's schema from it over the SDK bridge, so the picker always matches what your site can render. Blocks ship when you deploy your app - there is no separate block build or publish step. *** ## Layout blocks Header, footer and other shared regions are **layout blocks** - the same as page blocks but tagged with `layoutPositions` (e.g. `["header"]`) and rendered by `CmssyServerLayout` per position. *** ## Internationalization Content is language-keyed in the CMS and resolved per request. Routing is by path prefix (`/pl/*`), with the default locale using clean URLs. Read the active and enabled locales from `context.locale`. *** ## Next Steps - [Block Development](https://www.cmssy.com/docs/blocks/define.md) - full walkthrough: define, component, register, ship - [Schema & Field Types](https://www.cmssy.com/docs/blocks/fields.md) - every field type, repeaters, groups - [Advanced Features](https://www.cmssy.com/docs/blocks/advanced.md) - layout blocks, styling, server loaders --- title: "Define" description: "Build custom blocks with React for your headless cmssy site. defineBlock, fields, the block component, and locale context with @cmssy/react." url: https://www.cmssy.com/docs/blocks/define last_updated: 2026-06-29 --- # Define Build custom blocks for your headless Cmssy site - defineBlock, fields, the block component, and context. ## Block anatomy A Cmssy block lives in your own Next.js repo as a folder under `blocks/`: - **block.ts** - declares the block with `defineBlock` + `fields` (its type, label, and editable schema) - **Hero.tsx** - the React component that renders the content Register the block in `cmssy/blocks.ts`. The editor reads each block's schema over the SDK bridge, so adding a block to a page renders an editor form from your `fields`. *** ## Define a block ```typescript // blocks/hero/block.ts import { defineBlock, fields } from "@cmssy/react"; import Hero from "./Hero"; // Exported on its own, so the component can derive its props from it. export const heroProps = { heading: fields.text({ label: "Heading", defaultValue: "Welcome" }), body: fields.richText({ label: "Body" }), ctaUrl: fields.link({ label: "CTA URL", defaultValue: "/signup" }), showCta: fields.boolean({ label: "Show CTA", defaultValue: true }), }; export const heroBlock = defineBlock({ type: "hero", label: "Hero", component: Hero, props: heroProps, }); ``` Field types: `text`, `textarea`, `richText`, `markdown`, `number`, `date`, `datetime`, `boolean`, `color`, `media`, `link`, `url`, `email`, `select`, `radio`, `multiselect`, `relation`, `repeater`, `table`, `json`, `form`, `pageSelector`. See [Schema & Field Types](https://www.cmssy.com/docs/blocks/fields.md). *** ## The block component Blocks receive `{ content, context, data }`. The content is already resolved for the active locale, so read fields directly. ```tsx // blocks/hero/Hero.tsx import type { BlockProps } from "@cmssy/react"; import { heroProps } from "./block"; export default function Hero({ content, context }: BlockProps) { // Typed from the schema: heading is a string, showCta a boolean. const { heading, showCta, ctaUrl } = content; const isPreview = context?.isPreview ?? false; return (

{heading}

{showCta && Get started}
); } ``` `BlockProps` makes the schema the only place a field is named. Rename `heading` and the component stops compiling - instead of quietly rendering nothing, which is what reading `content.heading` off a `Record` would have done. When the block has a `loader`, pass its return type as the second argument: `BlockProps` types the `data` prop too. `context` carries `locale` (`{ current, default, enabled }`) and `isPreview` (`true` inside the editor), plus `forms` for any form the block references. `auth` and `workspace` are present when your app supplies them through `buildBlockContext`. Locale-aware UI reads `context.locale.enabled`. For your own models or records fetch with `createCmssyClient`; to fetch during SSR add a `loader` and read its result from `data`. See [Advanced Features](https://www.cmssy.com/docs/blocks/advanced.md) and [Server loaders](https://www.cmssy.com/docs/blocks/loaders.md). *** ## Register & ship ```typescript // cmssy/blocks.ts import { heroBlock } from "@/blocks/hero/block"; export const blocks = [heroBlock]; ``` Run `pnpm dev`, open the page editor, and your block appears in the picker. Deploy your Next.js app to ship - there is no separate block build or publish step. *** ## Next Steps - [Schema & Field Types](https://www.cmssy.com/docs/blocks/fields.md) - all field types, repeaters, conditional fields, groups - [Advanced Features](https://www.cmssy.com/docs/blocks/advanced.md) - layout blocks, styling, server loaders --- title: "Fields" description: "Every field type with its value type, the defineBlock + fields builder, field options, select options and repeaters." url: https://www.cmssy.com/docs/blocks/fields last_updated: 2026-09-09 --- # Fields All field types, the defineBlock + fields builder, field options, repeaters, and select options. ## All Field Types Define a block's editable props with the `fields.*()` builder inside `defineBlock`. Each builder returns a field definition; the key you give it in `props` becomes the content key. | Builder | Description | Value Type | | - | - | - | | `fields.text()` | Single-line text input | `string` | | `fields.textarea()` | Multi-line text area | `string` | | `fields.richText()` | WYSIWYG editor (Tiptap) | `string` (HTML) | | `fields.markdown()` | Markdown editor | `string` (Markdown) | | `fields.number()` | Number input | `number` | | `fields.date()` | Date picker | `string` (ISO date) | | `fields.datetime()` | Date & time picker | `string` (ISO) | | `fields.boolean()` | Toggle switch | `boolean` | | `fields.color()` | Color picker | `string` (hex) | | `fields.media()` | Image/video upload | `ResolvedMedia` or `ResolvedMedia[]` | | `fields.link()` | Internal/external link | `string` | | `fields.url()` | URL input | `string` | | `fields.email()` | Email input | `string` | | `fields.select()` | Dropdown (single choice) | `string` | | `fields.radio()` | Radio group (single choice) | `string` | | `fields.multiselect()` | Multiple choice | `string[]` | | `fields.relation()` | Reference records from a model | record or `record[]` | | `fields.repeater()` | Array of nested field groups | `object[]` | | `fields.table()` | Editable table grid | `{ columns, rows }` | | `fields.json()` | Raw JSON editor | JSON value | | `fields.form()` | Pick a Cmssy form | `string` (form id) | | `fields.pageSelector()` | Pick page(s) | `PageRef[]` | Most builders take only the base options below. `fields.select()`, `fields.radio()` and `fields.multiselect()` require an `options` array; `fields.media()` accepts `multiple`; `fields.relation()` needs a `model` (the referenced model's slug) and optionally `mode: "all"`, `multiple`, `sort` and `limit`. A relation stores record id(s); the delivery API resolves them to full records before your component renders. *** ## Defining a Block A block is declared with `defineBlock`. Its editable fields live under `props`: ```typescript import { defineBlock, fields } from "@cmssy/react"; import Hero from "./Hero"; export const heroProps = { heading: fields.text({ label: "Heading", required: true, defaultValue: "Welcome" }), description: fields.textarea({ label: "Description" }), }; export const heroBlock = defineBlock({ type: "hero", label: "Hero", component: Hero, props: heroProps, }); ``` Export the props object on its own and type the component from it - `BlockProps` - so the schema stays the only place a field is named, and the value types in the table above become the types your component sees. See [Block development](https://www.cmssy.com/docs/blocks/define.md). *** ## Field Options Every `fields.*()` builder accepts the same base options: ```typescript fields.text({ label: "Heading", required: true, defaultValue: "Welcome", placeholder: "Enter text", helperText: "Main heading", }) ``` Available keys: `label`, `required`, `defaultValue`, `placeholder`, `helperText`, `localized`. Select and repeater fields add a few more (below). *** ## Fields That Are the Same in Every Language By default every field is translated: each language holds its own value. A field that should hold **one** value for the whole site - a logo, a product photo, a brand colour - declares `localized: false`: ```typescript props: { logo: fields.media({ label: "Logo", localized: false }), heading: fields.text({ label: "Heading" }), } ``` The editor shows such a field once, with a padlock, whichever language you are editing; changing it changes it for every language. The delivery API still returns it inside every language's content, so your component reads `content.logo` exactly as before - nothing changes on the consumer side. `localized` is independent of `tab`: a field on the `style` or `advanced` tab is already one value per block, so the flag adds nothing there. Flipping the flag on an existing field moves the stored value for you on the next manifest push. Requires `@cmssy/core` 16.4.0 or newer. *** ## Select & Multiselect Options are a plain array of strings: ```typescript props: { layout: fields.select({ label: "Layout", options: ["grid", "list", "carousel"], defaultValue: "grid", }), tags: fields.multiselect({ label: "Tags", options: ["featured", "new"], }), } ``` *** ## Repeater (Arrays) Use `itemSchema` - a map of nested `fields.*()` - to describe each row: ```typescript props: { features: fields.repeater({ label: "Features", maxItems: 6, itemSchema: { icon: fields.text({ label: "Icon Name", defaultValue: "Star" }), title: fields.text({ label: "Title", required: true }), description: fields.textarea({ label: "Description" }), }, }), } ``` In your component: ```typescript export default function Features({ content }) { return (
{(content.features ?? []).map((f, i) => (

{f.title}

{f.description}

))}
); } ``` Repeater also supports `itemLabel`, `addButtonLabel`, `minItems`, `maxItems`, and `collapsible`. --- title: "Loaders" description: "Fetch a block's data on the server so it is crawlable, renders without a loading flash, and keeps server-only dependencies out of the client bundle." url: https://www.cmssy.com/docs/blocks/loaders --- # Loaders Fetch a block's data during server-side rendering so it is crawlable, renders without a loading flash, and keeps server-only dependencies out of the client bundle. A block's `loader` runs on the server during SSR and passes its result to the component as the `data` prop. Use it to fetch content, run heavy transforms, or call the delivery API before the page reaches the browser - instead of fetching client-side in a `useEffect`. Three things follow from that: - **SEO** - the content is in the server-rendered HTML, so crawlers see it. - **No flash** - the block renders populated on first paint. No skeleton. - **Smaller client bundle** - server-only dependencies like a syntax highlighter or an HTML sanitizer never reach the browser. ## The contract ```ts import { defineBlock } from "@cmssy/react"; defineBlock({ type: "my-block", loader: async ({ content, context }) => { // server-side during SSR only; returns RSC-serializable data return { html: "" }; }, component: MyBlock, // receives { content, context, data } }); ``` Three rules govern it: 1. The loader runs during SSR. **It does not run in the editor** - there the component receives `data: undefined`. Always render a sensible fallback. 2. The return value crosses the server-to-client boundary, so it must be **RSC-serializable**: plain objects, arrays and primitives. No functions, no class instances. 3. `content` is the block's resolved content; `context` is the block context (`locale`, `isPreview`, `forms`). Type `data` as optional and degrade when it is missing: ```tsx function MyBlock({ content, data, }: { content: Record; data?: { html?: string }; }) { if (!data?.html) return
{String(content.code ?? "")}
; // editor fallback return
; } ``` ## Keep server-only code out of the client bundle A block module is also reachable from the editor's client bundle. If your loader statically imports a heavy or server-only dependency, that dependency gets bundled for the browser too. Two guards prevent it: 1. **Dynamic `import()` inside the loader** - the dependency is pulled in only when the loader actually runs. 2. **A runtime `window` guard** in any shared server helper - a hard failure if it is ever reached on the client. ```ts // block.ts loader: async ({ content }) => { const code = typeof content.code === "string" ? content.code : ""; if (!code) return { html: "" }; const { codeToHtml } = await import("shiki"); // server-only, lazy return { html: await codeToHtml(code, { lang: "ts", theme: "github-light" }) }; }, ``` ```ts // load-posts.ts - a server-only helper, reached via dynamic import() import { createCmssyClient } from "@cmssy/react"; import { cmssy } from "@/cmssy/config"; const client = createCmssyClient(cmssy); export async function loadPosts(vars: { parentSlug: string; limit: number }) { if (typeof window !== "undefined") { throw new Error("loadPosts must only run on the server"); } return client.queryScoped(PUBLIC_PAGES_QUERY, vars); } ``` The loader itself stays tiny; the helper only ever loads on the server: ```ts loader: async ({ content }) => { const parentSlug = resolveParentSlug(content); if (!parentSlug) return null; const { loadPosts } = await import("./load-posts"); return loadPosts({ parentSlug, limit: Number(content.postsPerPage) || 9 }); }, ``` ## Calling the delivery API Use `createCmssyClient(...).queryScoped(...)` or `graphqlRequest` from `@cmssy/react`. `queryScoped` auto-injects the workspace id: when your query declares `$workspaceId` and you do not pass it, the SDK resolves it from your `workspaceSlug` and adds both the variable and the `x-workspace-id` header. You never manage the workspace id yourself. ## Hybrid: SSR the first page, then go client-side A loader does not have to own the data forever. A common pattern loads the first page on the server, seeds the client hook's initial state from `data`, and leaves search, pagination and filtering to the client: ```tsx function BlogPosts({ content, context, data }) { // seed initial state from the SSR `data`; client effects handle the rest const state = useBlogPosts(content, context, data); // ... } ``` When `data` is present the client skips its initial fetch entirely. Only user-driven actions - typing a search, scrolling for more - hit the network. ## Worked examples Three blocks in the cmssy-web reference app use loaders, each for a different reason: - `docs-code-block` - server-side syntax highlighting into `data.html`. Server-only dep: `shiki`. - `legal` - sanitizes CMS-authored HTML into `data.sections`. Server-only dep: `sanitize-html`. - `blog-posts` - fetches the first page of posts into `data.items`. Server-only dep: the delivery API. ## When a loader throws A loader that throws does not take the page down. The SDK catches it and contains the block: - **On your site** - the block renders nothing. The rest of the page is unaffected. - **In the editor** - a diagnostic card in the block's place, labelled *loader failed*, carrying the error message and the block id. The asymmetry is deliberate. Visitors should never meet a stack trace, and whoever is editing should never have to guess why a block went blank. It also means a failing loader is easy to miss in production - the page just quietly has one less section. If a block is absent from a live page and the content looks fine, open that page in the editor before suspecting the content. ## Checklist - Loader returns RSC-serializable data - plain objects, arrays, primitives. - Component renders a fallback when `data` is `undefined`, so the editor still works. - Server-only dependencies sit behind a dynamic `import()`. - Shared server helpers guard on `typeof window !== "undefined"`. - Delivery calls go through `queryScoped` or `graphqlRequest`, so the workspace is auto-scoped. ## Next steps - [Block development](https://www.cmssy.com/docs/blocks/define.md) - `defineBlock` end to end. - [Advanced block features](https://www.cmssy.com/docs/blocks/advanced.md) - context, preview behaviour, edge cases. - [API & AI](https://www.cmssy.com/docs/api.md) - what the delivery API exposes. --- title: "Advanced" description: "Layout blocks, server vs client components, and fetching data with createCmssyClient in headless cmssy." url: https://www.cmssy.com/docs/blocks/advanced last_updated: 2026-06-29 --- # Advanced Layout blocks, server vs client components, and fetching data with server loaders. ## Layout blocks Header, footer and other shared regions are **layout blocks** - the same as page blocks, but tagged with `layoutPositions` and rendered by `CmssyServerLayout` per position. ```typescript // blocks/header/block.ts import { defineBlock, fields } from "@cmssy/react"; import Header from "./Header"; export const headerBlock = defineBlock({ type: "header", label: "Header", layoutPositions: ["header"], component: Header, props: { logo: fields.media({ label: "Logo" }), links: fields.repeater({ label: "Navigation", itemSchema: { label: fields.text({ label: "Label" }), url: fields.link({ label: "URL" }), }, }), }, }); ``` Render the position in your route's layout with `CmssyServerLayout`, and through the edit bridge on the edit route - see [Layouts](https://www.cmssy.com/docs/rendering/layouts.md). *** ## Server & client components Blocks are standard Next.js components. By default they render as **server components** - zero client JS. Add `"use client"` at the top of a component only when it needs hooks, event handlers, browser APIs or client animations. ```tsx "use client"; import { useState } from "react"; export default function StatsCounter({ content }: { content: Record }) { const [n, setN] = useState(0); // ... } ``` > **Scroll / entrance animations need a client component.** If a block uses reveal-on-scroll (framer-motion `whileInView`, `initial={{ opacity: 0 }}`, IntersectionObserver), it must be a client component (`"use client"`) so the animation runs - otherwise the server HTML stays at `opacity:0` and the content never fades in on the published site (it looks fine in the editor, which renders client-side). *** ## Fetching data: server loaders Most blocks should fetch on the **server, during SSR**, via a `loader`. The loader runs in `CmssyServerPage` and passes its result to the component as the `data` prop - so the content lands in the server-rendered HTML (crawlable, no loading flash) and server-only dependencies never reach the client bundle. ```typescript import { defineBlock } from "@cmssy/react"; export const blogPostsBlock = defineBlock({ type: "blog-posts", component: BlogPosts, // receives { content, context, data } loader: async ({ content, context }) => { // runs on the server only; returns RSC-serializable data const { loadPosts } = await import("./load-posts"); return loadPosts({ limit: Number(content.postsPerPage) || 9 }); }, }); ``` The loader **does not run in the editor** - there the component receives `data: undefined`, so always render a sensible fallback. The return value crosses the server→client boundary, so it must be RSC-serializable: plain objects, arrays and primitives - no functions or class instances. Keep server-only or heavy dependencies behind a **dynamic `import()`** inside the loader (as above), and guard shared server helpers with `typeof window !== "undefined"` so they fail loudly if ever bundled for the browser. ### Calling the delivery API Use `createCmssyClient(...).queryScoped(...)` from `@cmssy/react`. `queryScoped` **auto-injects `workspaceId`**: when your query declares `$workspaceId` and you don't pass it, the SDK resolves it from your `workspaceSlug` and adds both the variable and the `x-workspace-id` header. ```typescript // load-posts.ts — a server-only helper, imported via dynamic import() import { createCmssyClient } from "@cmssy/react"; import { cmssy } from "@/cmssy.config"; const client = createCmssyClient(cmssy); export async function loadPosts(vars: { limit: number }) { if (typeof window !== "undefined") throw new Error("loadPosts is server-only"); return client.queryScoped(PUBLIC_PAGES_QUERY, vars); } ``` ### Client-side data & the block context For interactivity after first paint (search, pagination, filtering), seed client state from the SSR `data` and fetch the rest client-side with the same `createCmssyClient`. The block `context` also carries data you often need without a fetch: ```typescript context.locale; // { current, default, enabled } context.isPreview; // true inside the editor context.forms; // resolved form definitions (when present) context.auth; // { isAuthenticated, member } when your app supplies it context.workspace; // { id, slug } when resolved context.page; // { id, slug, pageType } - the page this block is on ``` See [Member Authentication](https://www.cmssy.com/docs/auth/members.md) for `context.auth` and the secure auth flow. `context.page` (SDK 10.2+) is how a block refers to itself: a related-posts loader excludes the current post by `context.page.id`, a section index lists the children of `context.page.slug`. It is identity only - no ancestors, no navigation tree - and it is absent on layout blocks, which belong to a layout rather than to one page. *** ## Next Steps - [Schema & Field Types](https://www.cmssy.com/docs/blocks/fields.md) - [Block System](https://www.cmssy.com/docs/blocks.md) - [Member Authentication](https://www.cmssy.com/docs/auth/members.md) - [MCP Server](https://www.cmssy.com/docs/api/mcp.md) --- title: "Testing" description: "A site whose editor is dead still compiles and still passes unit tests. checkCmssyEditMode is the check that catches it." url: https://www.cmssy.com/docs/blocks/testing --- # Testing The editor is the path your build cannot check. One smoke test covers it. A site whose editor is dead still compiles, still serves, and still passes your unit tests. Nothing in a normal build touches the edit path, so nothing in a normal build tells you when it breaks. `checkCmssyEditMode` is the check that does. ## The smoke test ```ts import { checkCmssyEditMode } from "@cmssy/next/testing"; const result = await checkCmssyEditMode({ baseUrl: "http://localhost:3000", secret: process.env.CMSSY_DRAFT_SECRET!, path: "/", // Only if your URLs carry the language. The check reads - a // contract - rather than hunting for a word from your copy, which an editor // can rewrite at any time. localizedPath: "/pl", }); expect(result.failures).toEqual([]); ``` Run it against a **started production build** (`next build && next start`), not the dev server. Static rendering is the thing that made the edit route necessary in the first place, so the dev server tests the wrong app. One more option exists for sites whose URL prefix is not the locale code. `localizedLocale` names the language `localizedPath` must render; it defaults to the first path segment, which *is* the language on a prefixed site. Set it explicitly when your prefix and your locale differ - `/en-gb` serving locale `en`, say - or the check compares against a language that does not exist and fails for the wrong reason. ## What it asserts 1. The public page returns 200 **without** the editor, with header and footer rendered server-side. 2. A bare `?cmssyEdit=1` with no secret does **not** enter edit mode. An unverified request must never open the door. 3. A verified `cmssyEdit=1` plus `cmssySecret` renders the editor **and** moves header and footer onto the edit bridge. 4. Optionally: the localized preview declares the language its URL asks for, via ``. ## Why "no header in the SSR" means success This is the assertion that reads backwards until you see why. In edit mode the header and footer mount through the edit bridge, which renders on the **client**. So a header still present in the server-rendered HTML is a header the editor can select but cannot edit - the difference between an editable block and plain markup. When it fails, the message names the cause rather than the symptom: ```text edit /shop: the header and footer are still server-rendered - they will be selectable but have no fields (is CMSSY_EDIT_HEADER set on the rewrite?) ``` ## In CI ```yaml - run: pnpm build - run: | pnpm start & npx wait-on http://localhost:3000 --timeout 60000 - run: pnpm smoke:edit ``` Skip the job when the workspace secrets are absent. A green check that verifies nothing is worse than no check - it converts an unknown into a false assurance. ## Wiring it as a script The reference app keeps it as a standalone script rather than a test-runner case, so it can run in CI without a framework: ```json { "scripts": { "smoke:edit": "node smoke-edit.mjs" } } ``` ```js // smoke-edit.mjs import { checkCmssyEditMode } from "@cmssy/next/testing"; const result = await checkCmssyEditMode({ baseUrl: "http://localhost:3000", secret: process.env.CMSSY_DRAFT_SECRET, localizedPath: "/pl", }); console.log(result.ok ? "EDITOR OK" : "EDITOR BROKEN"); for (const f of result.failures) console.log(" -", f); process.exit(result.ok ? 0 : 1); ``` ## What else to test Blocks are ordinary React components, so test them the ordinary way. Two cmssy-specific habits are worth keeping: - **Render each block with `data: undefined`** - that is what the editor passes, and a block that throws without its loader result is a block that breaks the editor. - **Render with a missing locale** - content may not be translated yet, and the fallback path is the one your visitors will hit first in a new language. ## Next steps - [Server loaders](https://www.cmssy.com/docs/blocks/loaders.md) - why `data` is undefined in the editor. - [Rendering](https://www.cmssy.com/docs/rendering.md) - the routes the smoke test exercises. - [Page builder](https://www.cmssy.com/docs/editor/page-builder.md) - what the editor does once it opens. --- title: "Rendering" description: "Render cmssy pages in your Next.js app: the catch-all route, createCmssyPage, owned SEO metadata via the gateway, layouts, localized routing and ISR revalidation." url: https://www.cmssy.com/docs/rendering --- # Rendering One catch-all route turns every published page - blocks, layout, SEO and locale - into server-rendered HTML on your own Next.js frontend. The catch-all route, page component, metadata, layout, localized routing and ISR revalidation. ## The catch-all route A cmssy workspace stores content; your app renders it. One optional catch-all route - `app/[[...path]]/page.tsx` - maps every published slug (and its locale prefix) to a page. `createCmssyPage` fetches the page for the current path, matches each block to your registered component and renders it on the server. > The catch-all is **statically renderable**: it never reads `searchParams` or `headers()`, so ISR stays on. Draft preview still works per-request through `draftMode()`. ### Next.js ```tsx import { createCmssyPage } from "@cmssy/next/server"; import { cmssy } from "@/cmssy.config"; import { blocks } from "@/cmssy/blocks"; export const revalidate = 3600; // The public route stays static. A verified editor request is rewritten by the // middleware onto app/cmssy-edit/[[...path]], mounted with createCmssyEditPage. export default createCmssyPage(cmssy, blocks); ``` ### Astro ```astro --- import { loadCmssyPage } from "@cmssy/astro"; import { cmssy } from "../cmssy.config"; import { Blocks } from "../components/Blocks"; export const prerender = false; const { page, locale, defaultLocale, enabledLocales } = await loadCmssyPage( cmssy, Astro.request, Astro.url, ); if (!page) { Astro.response.status = 404; } --- {page?.seoTitle?.[locale] ?? page?.displayName?.[locale] ?? "cmssy on Astro"} { page ? ( ) : (

Not found

) } ``` ### React Router ```tsx import { CmssyBlock, buildBlockContext, buildBlockMap } from "@cmssy/react"; import { createCmssyHeaders, createCmssyLoader } from "@cmssy/remix"; import { cmssy } from "../../cmssy.config"; import { blocks } from "../cmssy/blocks"; import { CmssyEditor } from "../cmssy/editor"; import type { Route } from "./+types/page"; export const loader = createCmssyLoader(cmssy); // Without these the admin cannot frame the site, and the editor shows an empty // box with no error anywhere. export const headers = createCmssyHeaders(cmssy); export default function CmssyPage({ loaderData }: Route.ComponentProps) { const { page, locale, defaultLocale, enabledLocales, isEdit, editorOrigin, diagnostics, } = loaderData; if (diagnostics) { return
; } // A verified editor request renders the same page through the edit bridge. // No separate route: a React Router page always sees its query string. if (isEdit) { return ( ); } if (!page) return (

Not found

); const blockMap = buildBlockMap(blocks); const context = buildBlockContext(locale, defaultLocale, enabledLocales); return (
{(page.blocks ?? []).map((block) => ( ))}
); } ``` `createCmssyPage(config, blocks, options?)` returns an async server component. `config` comes from `defineCmssyConfig`; `blocks` is the array of `defineBlock` definitions the SDK matches by `type`. Pass `{ editor }` to mount the visual editor on the preview route, or `{ path }` to pin a single-page route. ### Next.js ```typescript import { defineCmssyConfig } from "@cmssy/next"; // Pass process.env raw: defineCmssyConfig validates at startup and names any // variable you are missing. A `?? ""` fallback would hide that, and the error // would surface later, somewhere unrelated. // // This module reads server env. Never import a VALUE from it (or from a module // that imports it) in a "use client" component - types are erased, values drag // process.env into the browser bundle. export const cmssy = defineCmssyConfig({ org: process.env.CMSSY_ORG_SLUG, workspaceSlug: process.env.CMSSY_WORKSPACE_SLUG, draftSecret: process.env.CMSSY_DRAFT_SECRET, }); ``` ### Astro ```typescript import { defineCmssyConfig } from "@cmssy/astro"; // Pass the env raw: a `?? ""` fallback turns a missing variable into an empty // one, and the error then surfaces somewhere unrelated. export const cmssy = defineCmssyConfig({ org: process.env.CMSSY_ORG_SLUG, workspaceSlug: process.env.CMSSY_WORKSPACE_SLUG, draftSecret: process.env.CMSSY_DRAFT_SECRET, }); ``` ### React Router ```typescript import { defineCmssyConfig } from "@cmssy/remix"; // Pass the env raw: a `?? ""` fallback turns a missing variable into an empty // one, and the error then surfaces somewhere unrelated. export const cmssy = defineCmssyConfig({ org: process.env.CMSSY_ORG_SLUG, workspaceSlug: process.env.CMSSY_WORKSPACE_SLUG, draftSecret: process.env.CMSSY_DRAFT_SECRET, }); ``` The catch-all route, page component, metadata, layout, localized routing and ISR revalidation. The wiring, one concern per page. Read them in order the first time; after that, jump. - [Routes and pages](https://www.cmssy.com/docs/rendering/pages.md) - config, middleware, the public catch-all and the edit route. Copy it whole: the pieces depend on each other. - [Layouts](https://www.cmssy.com/docs/rendering/layouts.md) - header and footer as editable blocks, and why leaving out the editable wrapper breaks silently. - [Draft preview](https://www.cmssy.com/docs/rendering/draft-preview.md) - the three ways to see unpublished content, and the secret behind each. - [i18n](https://www.cmssy.com/docs/rendering/i18n.md) - locales, URL prefixes, and what renders when a translation is missing. - [SEO](https://www.cmssy.com/docs/rendering/seo.md) - metadata, sitemap and robots, all owned by your app. - [Scripts](https://www.cmssy.com/docs/rendering/scripts.md) - analytics and third-party tags, and the CSP that blocks them. One thing to carry into all of them: the SDK renders blocks and mounts the editor, and stops there. Metadata, the sitemap, locale helpers and the member session are your app's own code - see [the delivery API](https://www.cmssy.com/docs/api/graphql.md) for what you query directly. --- title: "Pages" description: "Three request shapes reach your app and need three different things. The config, middleware, public route and edit route that serve them." url: https://www.cmssy.com/docs/rendering/pages --- # Pages Three request shapes reach your app and need three different things. This is the wiring that serves all three. Copy this whole. The pieces depend on each other, and the dependencies are not obvious. ## The mental model Three request shapes reach your app, and each needs something different: - **A visitor** - published content, server-rendered, static where possible. Speed, and the CMS staying out of the render path. - **Draft preview** (the `/api/draft` cookie) - *draft* content on the *public* route, no editor. Someone reviewing a change, not editing it. - **The editor iframe** (`cmssyEdit=1` plus a matching `cmssySecret`) - draft content *plus* the edit bridge, on its own dynamic route. That third row is the one that surprises people. A static page never sees the query string, so it cannot know it is being edited. That is why `/cmssy-edit` exists, and everything below follows from it. ## 1. Config ```ts // cmssy.config.ts import { defineCmssyConfig } from "@cmssy/next"; export const cmssy = defineCmssyConfig({ org: process.env.CMSSY_ORG_SLUG, workspaceSlug: process.env.CMSSY_WORKSPACE_SLUG, draftSecret: process.env.CMSSY_DRAFT_SECRET, }); ``` Pass `process.env` **raw**. A `?? ""` fallback turns a missing variable into an empty one, and the error then surfaces later, somewhere unrelated. This module reads server env. Never import a **value** from it - or from a module that imports it - in a `"use client"` component. Types are fine, they are erased. Values drag `process.env` into the browser bundle. ## 2. Middleware ```ts // proxy.ts import { createCmssyProxy } from "@cmssy/next/middleware"; import { cmssy } from "@/cmssy.config"; export const proxy = createCmssyProxy(cmssy); // Static routes instead of a catch-all? Then, and only then, add // { stripLocalePrefix: true } - it would break a catch-all app. // Next parses this at compile time, so the matcher must be a literal - // an imported constant is rejected. export const config = { matcher: ["/((?!_next/|api/|.*\\..*).*)"] }; ``` The preset resolves the language, sends verified editor traffic to `/cmssy-edit` carrying that language and the edit flag, applies the CSP that lets the admin frame your site, and strips a language prefix if you asked - in that order. The order is not a detail, and each way of getting it wrong has already shipped once: - **Resolve the locale after the rewrite** and the editor preview renders in the wrong language - a route cannot read a prefix it never sees. - **Forget the edit flag** and the header and footer arrive as markup the editor can select but not fill. ## 3. The public page One catch-all route renders every published page. Metadata comes from a helper you own, built on the delivery API - the SDK hands you data, your app owns its routes: ```tsx // app/[[...path]]/page.tsx import { createCmssyPage } from "@cmssy/next/server"; import { cmssy } from "@/cmssy.config"; import { blocks } from "@/cmssy/blocks"; import { buildPageMetadata } from "@/services/seo"; export const revalidate = 3600; export const dynamicParams = true; export async function generateMetadata({ params }) { const { path } = await params; // As routed, prefix and all: the prefix IS the language. return buildPageMetadata(path); } export default createCmssyPage(cmssy, blocks); ``` `buildPageMetadata` is yours, not the SDK's. It queries the page's SEO fields and returns a Next.js `Metadata` object - see [SEO](https://www.cmssy.com/docs/rendering/seo.md) for what it contains. ## 4. The edit route ```tsx // app/cmssy-edit/[[...path]]/page.tsx import { createCmssyEditPage } from "@cmssy/next/server"; import { cmssy } from "@/cmssy.config"; import { blocks } from "@/cmssy/blocks"; import { CmssyEditor } from "@/cmssy/editor"; export const dynamic = "force-dynamic"; export default createCmssyEditPage(cmssy, blocks, { editor: CmssyEditor }); ``` Skip this file and the editor preview is blank. It is the single most common way to break a cmssy app, and nothing in a build will warn you - see [testing](https://www.cmssy.com/docs/blocks/testing.md). ## 5. The editor bridge ```tsx // cmssy/editor.tsx "use client"; import { CmssyLazyEditor } from "@cmssy/react/client"; import type { CmssyEditorProps } from "@cmssy/next"; export function CmssyEditor(props: CmssyEditorProps) { return import("./blocks")} />; } ``` The registry is loaded lazily **on the client**, so your block loaders - which run server-side and read the config - never reach the browser bundle. ## Caching Publishing does not deploy. The public route caches according to its own `revalidate`, and cmssy can call a revalidation webhook on publish to invalidate sooner: ```ts export const revalidate = 3600; export const dynamicParams = true; ``` The edit route is the exception: it is `force-dynamic` on purpose, because a cached edit page would show yesterday's draft. ## Next steps - [Layouts](https://www.cmssy.com/docs/rendering/layouts.md) - header and footer as editable blocks. - [Testing](https://www.cmssy.com/docs/blocks/testing.md) - proving the edit route still works. - [How cmssy works](https://www.cmssy.com/docs/start/how-it-works.md) - what happens between request and render. --- title: "Layout regions" description: "Declare your layout regions in cmssy.config.ts with defineCmssyLayout. The editor lists exactly those, and the slots are typed to them." url: https://www.cmssy.com/docs/rendering/layout-regions --- # Layout regions Your site declares which regions a layout block can live in. The editor lists exactly those. Header and footer are not the only places a layout block can live. Since cmssy-sdk 13 the **site declares its regions** in `cmssy.config.ts`, and the editor lists exactly those under Layouts. A sidebar, a top bar, a cookie strip - whatever your app actually mounts. If you declare nothing, you get `header` and `footer`, the same as before. ## Declaring regions ```ts // cmssy.config.ts import { defineCmssyConfig, defineCmssyLayout } from "@cmssy/next"; export const layout = defineCmssyLayout({ regions: [ { id: "header", label: "Header" }, { id: "sidebar", label: "Sidebar" }, { id: "footer", label: "Footer" }, ], }); export const cmssy = defineCmssyConfig({ org: process.env.CMSSY_ORG_SLUG, workspaceSlug: process.env.CMSSY_WORKSPACE_SLUG, draftSecret: process.env.CMSSY_DRAFT_SECRET, apiUrl: process.env.CMSSY_API_URL, // optional - SDK reads CMSSY_API_URL itself; falls back to https://api.cmssy.io/graphql layout, // optional - omit for header and footer only }); ``` An `id` starts with a letter or digit and continues with letters, digits, `_` or `-` (up to 50 characters). Ids are unique, labels are what the editor shows, and a layout holds at most 20 regions. `defineCmssyLayout` throws at startup on anything else - a typo does not reach the editor. Keep the `regions` array inline in the call. Hoisted into a variable first, TypeScript widens the ids to `string` and you lose the typing below. ## Typed slots `CmssyRegion` is the union of your declared ids. Type the slot helper with it and a slot for a region you never declared does not compile: ```tsx import type { CmssyRegion } from "@cmssy/next"; import { cmssy, type layout } from "@/cmssy.config"; const slot = (position: CmssyRegion) => ( ); {slot("header")}
{slot("footer")} ``` Import `layout` as a type only. The config module reads server env, and a value import from a client component would pull it into the browser bundle. The slot fetches the layouts of the routed page - `path` decides, and a page inherits its parent's regions as usual. Pass `page` only to pin a slot to one page regardless of the route (with the `locale` form, which has no path, you have to). With `cache` set, the slot reads layouts by key (cmssy-sdk 19.35): it first asks for a small key naming the page the layout comes from, then reads the layouts by that key. Every page that inherits the same layout sends the same request, so the data cache answers it once, and a static build pays for each distinct layout once instead of once per page. Without `cache`, in preview and in the editor, the slot reads the page's layouts directly. ## Which blocks a region accepts A block opts into regions with `layoutRegions`. The editor offers it only in those regions: ```ts export const sidebarNavBlock = defineBlock({ type: "sidebarNav", label: "Sidebar navigation", layoutRegions: ["sidebar"], component: SidebarNav, props: sidebarNavProps, }); ``` A block without `layoutRegions` is a page block and never appears in a layout. Before cmssy-sdk 15 the option was called `layoutPositions`. `npx @cmssy/codemod v15` renames it across your code. ## Region settings A region can carry its own settings, declared with the same `fields.*` builders a block uses for its props. cmssy invents none of them - a header has no width, a sidebar has whatever you say it has: ```ts import { fields } from "@cmssy/react"; export const layout = defineCmssyLayout({ regions: [ { id: "header", label: "Header" }, { id: "sidebar", label: "Sidebar", settings: { width: fields.number({ label: "Width (rem)" }), sticky: fields.boolean({ label: "Sticky" }), }, }, { id: "footer", label: "Footer" }, ], }); ``` The Layouts page renders a form under the region from that schema - a region without `settings` shows no form. Values are saved per page and inherited down the tree like the blocks themselves, and are validated against your schema on write: an unknown key is refused. Delivery returns them as `settings` on the layout group, typed with `CmssyRegionSettings`: ```tsx import type { CmssyRegionSettings } from "@cmssy/next"; type SidebarSettings = CmssyRegionSettings; // { width?: number; sticky?: boolean } const sidebar = groups.find((g) => g.position === "sidebar")?.settings as SidebarSettings | null; ``` Requires cmssy-sdk 14. On 13 the delivery query still asks for the old fixed settings shape and fails against the current API - upgrade before deploying. ## How the editor learns about them On Next, `createCmssyPage` and `createCmssyEditPage` forward the regions to the editor on their own. On Astro and React Router, `loadCmssyPage` / `createCmssyLoader` return `layoutRegions` - pass it to `CmssyEditor` as `edit={{ editorOrigin, layoutRegions }}`. Delivery returns the layout groups keyed by your ids, so `groups.find(g => g.position === "sidebar")` works as you would expect. ## Removing a region Take a region out of `regions` and its blocks are not deleted. The editor keeps the card, marks it as not mounted by the site, and lets you move or remove the blocks yourself. Nothing disappears from a page because a deploy changed a config file. Requires TypeScript 5.0 or newer (the typing relies on `const` type parameters). See [Layouts](https://www.cmssy.com/docs/rendering/layouts.md) for inheritance and the public/edit split, and the sdk migration guide [`v12-to-v13`](https://github.com/cmssy-io/cmssy-sdk/blob/main/docs/migrations/v12-to-v13.md) for the rename from `LayoutPosition`. --- title: "Layouts" description: "Header and footer are layout blocks, inherited down the page tree and editable like any other block." url: https://www.cmssy.com/docs/rendering/layouts --- # Layouts Header and footer are layout blocks - inherited down the page tree and editable like any other block. A header is not a component you hardcode into `app/layout.tsx`. In cmssy it is a **layout block**: the same kind of thing as a hero or a pricing table, stored in the CMS, edited in the page builder, and rendered by a component from your registry. That is a design decision with a consequence. If the header were markup, an editor could not change a nav link without a deploy. Because it is a block, they can. ## Positions and inheritance Layout blocks live at named positions - `header` and `footer` by default, or whatever your site declares (see [Layout regions](https://www.cmssy.com/docs/rendering/layout-regions.md)). A page either owns its layout or inherits it from its parent, so setting the header once on your root page gives it to the whole tree. Override it only where a section genuinely differs: a landing page with no navigation, a checkout with a stripped footer. Everything else inherits, which means one edit updates every page that did not opt out. ## Two root layouts, not one The public route and the edit route each have their own root layout. They fetch the same layout groups and render them through different components, because a server-rendered header cannot be edited and a client-mounted one cannot be static. You fetch the groups yourself - one delivery query, returning the layout blocks for a page: ```ts // services/layout.ts export async function fetchChromeLayouts( pageSlug: string, previewSecret?: string, ): Promise { /* PublicPageLayouts query */ } ``` ## The public layout `CmssyServerLayout` from `@cmssy/react` renders the groups server-side. It needs the block registry, because it resolves types on the server: ```tsx // app/[[...path]]/layout.tsx import { CmssyServerLayout } from "@cmssy/react"; const { isEnabled: draft } = await draftMode(); const [locales, groups] = await Promise.all([ resolveSiteLocales(), fetchChromeLayouts("/", draft ? cmssy.draftSecret : undefined), ]); const slot = (position: "header" | "footer") => ( ); ``` The draft secret is passed **only when draft mode is on**. Pass it unconditionally and your public site starts serving unpublished header changes. ## The edit layout The edit route renders the same groups through your client wrapper instead: ```tsx // app/cmssy-edit/[[...path]]/layout.tsx const slot = (position: "header" | "footer") => ( ); ``` Note what is missing: no `blocks` prop. The registry is loaded lazily on the client by the wrapper itself: ```tsx // cmssy/editable-layout.tsx "use client"; import { CmssyLazyLayout, type CmssyLazyLayoutProps } from "@cmssy/react/client"; export function EditableLayout(props: Omit) { return import("./blocks")} />; } ``` Lazy loading here is not an optimisation, it is a boundary. Block modules can contain server loaders that read config and server-only dependencies; importing the registry eagerly from a client component would drag all of it into the browser bundle. Both root layouts must set `` from the resolved locale - the edit one included, because the preview has to declare the language it is actually rendering. ## Why this is the part that breaks silently Omit `editable` and everything still looks right. The site builds, visitors see the correct header, your tests pass. But in the editor the header is now server-rendered markup. It is selectable and has no fields - the editor can highlight it and change nothing. There is no error, no warning, no red build. This is exactly what `checkCmssyEditMode` asserts, and why its success condition reads backwards: *no* `
` in the server-rendered HTML of an edit-mode request is the passing state. See [testing](https://www.cmssy.com/docs/blocks/testing.md). ## Next steps - [Routes and pages](https://www.cmssy.com/docs/rendering/pages.md) - the routes these slots sit inside. - [Layout regions](https://www.cmssy.com/docs/rendering/layout-regions.md) - declaring a sidebar or any other region. - [Testing](https://www.cmssy.com/docs/blocks/testing.md) - the smoke check that catches a dead layout. - [Page builder](https://www.cmssy.com/docs/editor/page-builder.md) - editing layout blocks in practice. --- title: "Draft Preview" description: "The delivery API returns published content only. Three mechanisms let the right people see drafts without opening that door to everyone." url: https://www.cmssy.com/docs/rendering/draft-preview --- # Draft Preview The delivery API returns published content only. Three mechanisms let the right people see drafts without opening that door to everyone. Public reads return published content and nothing else. That is a property of the API, not a filter your app remembers to apply - which is why an unfinished page cannot leak by accident. It also means seeing a draft requires deliberately proving who you are. There are three ways, for three different people. ## 1. Draft cookie - for reviewers A colleague reviewing a change wants the draft on the real URL, without an editor in the way. The `/api/draft` route sets a cookie that flips the public route to draft content: ```text /api/draft?secret=...&slug=/pricing ``` The route validates the secret against `CMSSY_DRAFT_SECRET`, sets the cookie, and redirects to the slug. From then on that browser sees drafts until the cookie is cleared. Everyone else keeps seeing the published site. ## 2. Dev draft overlay - for you, while developing Append `?cmssyDev=1` to any URL to render your own **per-user draft overlay**: ```text http://localhost:3000/pricing?cmssyDev=1 ``` This is not the shared draft. It is your personal working copy, which is what makes it safe for trying a block that is not deployed yet - nobody else's preview changes. It requires `CMSSY_API_TOKEN` and is meant for development. Without the flag you get published content, so leaving the token set does not change what visitors see. ## 3. Edit mode - for the editor The editor iframe sends `cmssyEdit=1` plus a matching `cmssySecret`. The middleware verifies the pair and rewrites to `/cmssy-edit`, which serves draft content *and* mounts the edit bridge. An unverified `?cmssyEdit=1` does nothing. That is asserted by the smoke test, because a preview route that trusts a query string is a public draft leak with extra steps - see [testing](https://www.cmssy.com/docs/blocks/testing.md). ## The secrets - `CMSSY_DRAFT_SECRET` - guards the draft-preview bridge and edit mode. Generated by cmssy for each workspace - not a string you invent. `cmssy link` writes it to `.env.local`, and it is shown under Settings → Headless. - `CMSSY_API_TOKEN` - required for the `?cmssyDev=1` overlay, because reading someone's personal draft is an authenticated operation. - `CMSSY_WEBHOOK_SECRET` - guards the `/api/revalidate` webhook, which is a different concern: it invalidates cache after publish, and does not expose drafts. ## Publishing and the cache Publishing does not deploy, and it does not automatically show up either. Your public route caches to its own `revalidate` value, so a freshly published page can keep serving the old copy until that window passes. The `/api/revalidate` webhook closes that gap: cmssy calls it on publish, and the route invalidates the affected paths. If a change is published but the site still shows the old version, check that webhook before suspecting the CMS. ## Next steps - [Routes and pages](https://www.cmssy.com/docs/rendering/pages.md) - the three request shapes these mechanisms serve. - [Testing](https://www.cmssy.com/docs/blocks/testing.md) - proving edit mode still rejects unverified requests. - [API tokens](https://www.cmssy.com/docs/auth/api-tokens.md) - creating and scoping `CMSSY_API_TOKEN`. --- title: "i18n" description: "Every field is multilingual by default. How locales shape URLs, which one a request resolves to, and what happens when a translation is missing." url: https://www.cmssy.com/docs/rendering/i18n --- # i18n Every field is multilingual by default. How locales shape URLs, which one a request resolves to, and what happens when a translation is missing. You do not model translations in cmssy. Every field is multilingual already: content is stored keyed by language code, so one page carries all its languages and one block instance carries all of its. That removes the usual duplication problem - there is no "English page" and "German page" to keep in sync - and replaces it with two smaller questions. Which locale does a request resolve to, and what shows when a field has not been translated yet? One thing to settle before the code below: since the slim 10.x release the SDK ships **no** locale helpers. `resolveSiteLocales`, `localizedPath`, `splitLocaleFromPath` and `pickLocalized` in these snippets are your app's own - about forty lines in `lib/`, shared by the catch-all route, the sitemap and `generateMetadata`. The rules they implement belong to cmssy; the code belongs to you. (Equivalents live under `@cmssy/core/internal`, but internal means they can move without a breaking-change note.) ## The locale set Locales come from your site config, not from your code: ```ts const { defaultLocale, locales } = await resolveSiteLocales(); ``` Adding a language is a workspace setting. Your app picks it up on the next request, which means a new locale does not need a deploy - only translations. ## URLs: the default locale has no prefix This is the rule everything else follows from: ```ts localizedPath("/pricing", "en", "en"); // "/pricing" default: bare localizedPath("/pricing", "de", "en"); // "/de/pricing" others: prefixed localizedPath("/", "de", "en"); // "/de" ``` Keeping the default locale unprefixed means your canonical URLs never change when you add a second language - existing links, shares and rankings all survive. ## Resolving a request The reverse direction reads the first path segment, and it is deliberately strict: ```ts splitLocaleFromPath(["de", "pricing"], { defaultLocale: "en", locales: ["en", "de"] }); // -> { locale: "de", path: ["pricing"] } splitLocaleFromPath(["pricing"], { defaultLocale: "en", locales: ["en", "de"] }); // -> { locale: "en", path: ["pricing"] } ``` A first segment counts as a locale only when it is in `locales` **and** is not the default. So `/en/pricing` is not the English pricing page - it is a page whose slug happens to start with `en`. One canonical URL per page per language, no duplicates. The catch-all route does this before looking up a slug: ```tsx const { path: strippedPath } = splitLocaleFromPath(path, await resolveSiteLocales()); const slug = "/" + (strippedPath ?? []).join("/"); ``` ## Missing translations A field falls back rather than disappearing: ```ts pickLocalized(value, locale, defaultLocale); // value[locale] ?? value[defaultLocale] ?? first available value ``` Three steps: the requested language, then the default, then whatever exists. The last one matters - a field translated only into French still renders on a German page rather than leaving a hole. The consequence for block authors: **a partially translated page is a normal state**, not an error. Write components that render sensibly when a field comes back in the wrong language, and test with a locale you have not translated - it is the first thing your visitors will hit in a new language. ## Middleware ```ts // proxy.ts export const proxy = createCmssyProxy(cmssy); // Static routes instead of a catch-all? Then, and only then: // createCmssyProxy(cmssy, { stripLocalePrefix: true }); ``` The SDK is explicit about this: leave it off for a catch-all app that reads the language off the path itself. Turn it on anyway and the route receives a path with no prefix, so `splitLocaleFromPath` finds nothing to strip and falls back to the default locale - every language renders as the default one. The middleware does still resolve the language and pass it on in a header, so an app can read it from there instead. But if your route derives the locale from the path, as a catch-all normally does, those two are now telling it different things. ## Declare the language in HTML Set `` from the resolved locale. It is what screen readers and translation tools read, and it is a *contract* - which is why the editor smoke test asserts against it rather than searching for a word in your copy. Copy is content; an editor can rewrite it at any time, and then the test lies. ## Next steps - [SEO](https://www.cmssy.com/docs/rendering/seo.md) - hreflang alternates built from the same locale set. - [Testing](https://www.cmssy.com/docs/blocks/testing.md) - the `` assertion. - [Data models](https://www.cmssy.com/docs/content/data-models.md) - records are multilingual too. --- title: "SEO" description: "Per-page metadata, a sitemap built from the published page tree, and a robots file that keeps the edit route out of the index." url: https://www.cmssy.com/docs/rendering/seo --- # SEO Per-page metadata, a sitemap built from the published page tree, and a robots file that keeps the edit route out of the index. SEO fields are content, so editors own them. Your app's job is to read them and hand Next.js the right shapes. ## Page metadata Every page carries `seoTitle`, `seoDescription`, `seoKeywords` and `displayName`, each multilingual. The SDK ships **no** metadata helper - `generateMetadata` is your route's own code, and that is deliberate: canonical host, title template and OG strategy are decisions about your site, not about the CMS. ```tsx // app/[[...path]]/page.tsx import type { Metadata } from "next"; import { buildPageMetadata } from "@/services/seo"; type PageProps = { params: Promise<{ path?: string[] }> }; export async function generateMetadata({ params }: PageProps): Promise { const { path } = await params; // As routed, prefix and all: the prefix IS the language. return buildPageMetadata(path); } ``` `buildPageMetadata` is yours. It splits the locale off the path, reads the SEO fields through `public.page.get`, and returns a Next.js `Metadata` object: ```ts // services/seo.ts (abridged) const { locale, path: rest } = splitLocaleFromPath(path, { defaultLocale, locales }); const slug = "/" + (rest ?? []).join("/"); const meta = (await publicRequest(PAGE_META_QUERY, { workspaceSlug, slug })).public.page.get; const title = pickLocalized(meta?.seoTitle, locale, defaultLocale) || pickLocalized(meta?.displayName, locale, defaultLocale) || siteName; return { title, description: pickLocalized(meta?.seoDescription, locale, defaultLocale) || undefined, keywords: meta?.seoKeywords?.length ? meta.seoKeywords : undefined, alternates: { canonical: `${SITE_URL}${localizedPath(slug, locale, defaultLocale)}`, languages: Object.fromEntries( locales.map((l) => [l, `${SITE_URL}${localizedPath(slug, l, defaultLocale)}`]), ), }, openGraph: { title, images: siteConfig?.branding?.ogImageUrl }, }; ``` `splitLocaleFromPath`, `localizedPath` and `pickLocalized` are your app's helpers too - forty lines in `lib/`, shared with the catch-all route and the sitemap. `SITE_URL` is your own env var; the CMS never stores your host. Fall back deliberately: `seoTitle`, then `displayName`, then the site name - so a half-finished page still has a title. The Open Graph default comes from `public.siteConfig`'s [branding](https://www.cmssy.com/docs/editor/branding.md). ## Sitemap and robots are your routes cmssy does not ship a sitemap helper, and that is the headless model working as intended. A sitemap is a query plus a mapping to whatever shape your framework wants - the CMS has no business owning your route file. The published page tree already *is* the sitemap. Query it, map it: ```ts // app/sitemap.ts import { listPublicPages } from "@/services/pages"; import { fetchSiteConfig, resolveSiteLocales } from "@/services/site"; import { localizedPath } from "@/lib/locale-path"; export const dynamic = "force-dynamic"; export default async function sitemap() { const [{ defaultLocale, locales }, pages, siteConfig] = await Promise.all([ resolveSiteLocales(), listPublicPages(), fetchSiteConfig(), ]); const notFoundPageId = siteConfig?.notFoundPageId ?? null; return pages .filter((page) => page.publishedAt && page.id !== notFoundPageId) .map((page) => ({ url: `${SITE_URL}${localizedPath(page.slug, defaultLocale, defaultLocale)}`, lastModified: new Date(page.updatedAt ?? page.publishedAt), alternates: { languages: Object.fromEntries( locales.map((l) => [l, `${SITE_URL}${localizedPath(page.slug, l, defaultLocale)}`]), ), }, })); } ``` Two filters, two different reasons. `publishedAt` - `public.page.list` returns drafts too, and they have no business in a sitemap. `notFoundPageId` - the 404 page is published like any other, and listing it invites crawlers to index an error; the workspace already says which page it is, through `siteConfig`. ### Keep it a helper, not a route body Put the querying and mapping in `services/` and let the route file stay four lines. Products or categories from model records are not pages, so the page tree does not know about them - when you add them, you want one function that owns URL shape and hreflang for every entry, not two places that can disagree about the domain. This is also what makes the pattern portable. The same helper, with a different return shape, feeds an Astro or Remix app - the query is the reusable part, the route is the adapter. ## Robots ```ts // app/robots.ts export const dynamic = "force-dynamic"; export default function robots() { return { rules: { userAgent: "*", allow: "/", disallow: ["/cmssy-edit/", "/api/"], }, sitemap: `${SITE_URL}/sitemap.xml`, }; } ``` **Disallowing `/cmssy-edit/` is not optional.** That route serves draft content and mounts the editor. Indexed, it would put unpublished copy in search results and rank a duplicate of every page you have. ## Both routes must be dynamic ```ts export const dynamic = "force-dynamic"; ``` Sitemaps and robots read live CMS state. Statically generated at build time, your sitemap freezes on the day you deployed and quietly stops listing everything published since. ## Next steps - [i18n](https://www.cmssy.com/docs/rendering/i18n.md) - how locales shape URLs and hreflang. - [Routes and pages](https://www.cmssy.com/docs/rendering/pages.md) - where `generateMetadata` lives. - [Branding](https://www.cmssy.com/docs/editor/branding.md) - the site config behind Open Graph images. --- title: "Scripts" description: "Analytics and tag scripts are app code, not content. Where to mount them, which loading strategy to pick, and why the editor's CSP matters." url: https://www.cmssy.com/docs/rendering/scripts --- # Scripts Analytics and tag scripts are app code, not content. Where to mount them, which loading strategy to pick, and why the editor's CSP matters. Analytics, tag managers, chat widgets, consent banners - these belong in your app, not in the CMS. The reason is ownership. A script tag is executable code on every page; it is reviewed, versioned and deployed like the rest of your app. Putting one in an editable field turns "change a heading" and "run arbitrary JavaScript on production" into the same permission. ## Analytics: use the official components For Google Analytics and Tag Manager, do not hand-roll a script tag. `@next/third-parties` ships components that load the script *and* the init snippet with the right strategy: ```tsx // app/[[...path]]/layout.tsx import { GoogleAnalytics, GoogleTagManager } from "@next/third-parties/google"; const gaId = process.env.NEXT_PUBLIC_GA_ID?.trim(); const gtmId = process.env.NEXT_PUBLIC_GTM_ID?.trim(); // ...inside {gtmId ? : null} {gaId ? : null} ``` A raw `