# Introduction (/docs/brand)
The Brand section collects what makes VitNode look like VitNode, so your
community, plugin or blog post can use it without guessing. Everything here
ships in `@vitnode/core` or downloads straight from the page.
## What's here [#whats-here]
- **Tabby, the pet.** A striped hexagon cat with 14 states, from `hello` to
`dizzy`. Its body is the logo's hexagon and its colors are the logo's blues,
so it never looks off-brand next to the mark.
- **The palette.** Tabby and the logo use the same blues as the UI's primary
color, documented with every other token on the Colors page.
## Related [#related]
# Pet (/docs/brand/pet)
Tabby is VitNode's pet: a striped hexagon cat that ships as one React component
with 14 states. Drop it into an empty state, a loading screen or an error page
and the page instantly feels less like a stack trace.
## Use the pet [#use-the-pet]
Import `Pet` from core and pick a `state`. The pet scales to its box, so size it
with Tailwind classes. Keep roughly a 7:8 width-to-height ratio.
```tsx title="welcome.tsx"
import { Pet } from '@vitnode/core/components/pet/pet'
export const Welcome = () =>
```
## States [#states]
Every card has three buttons:
- **Copy** puts the SVG markup on your clipboard, ready to paste into code or a
design tool.
- **SVG** downloads an animated file. The animation styles travel inside it, so
Tabby keeps moving wherever you open it.
- **PNG** downloads a still, 1024 px wide image with a transparent background.
| State | Use it for |
| ----------- | ------------------------------ |
| `idle` | Default pose |
| `hello` | Onboarding and welcome screens |
| `coding` | Docs and developer pages |
| `coffee` | Breaks and quiet days |
| `love` | Thank-you screens |
| `music` | Media and playlists |
| `sleeping` | Idle or maintenance mode |
| `thinking` | Loading states |
| `celebrate` | Success and first publish |
| `searching` | Empty search results |
| `offline` | Lost connections |
| `oops` | 404 pages |
| `dizzy` | 500 errors |
| `building` | Maintenance and coming soon |
## Error pages [#error-pages]
`ErrorContent` draws the status code in huge digits and lets Tabby stand in for
the middle one: a 404 shows `oops` between the two 4s, and a 500 shows `dizzy`
between the 5 and the 0. The built-in pages need no extra code. Other codes, such
as 403, keep all three digits and skip the pet. Screen readers hear the code and
title together, not the decorative digits.
## Props [#props]
## Accessibility [#accessibility]
- The pet is decorative by default (`aria-hidden`). When it is the only thing
that explains the screen, pass a `label` and it becomes an image with that
name.
- Only parts move: tail, ears, blinks, paws and props. The body never floats.
- All animation stops when the visitor turns on reduced motion.
## Related [#related]
# Access rules API (/docs/content-engine/access-api)
Exact names, values and behavior of Content Engine access rules. For a guided setup, follow [Access rules](/docs/content-engine/access) or [Category access](/docs/content-engine/access-categories). [How access is enforced](/docs/content-engine/access-behavior) explains where the rules apply.
## `access` option [#access-option]
### Container collection [#container-collection]
`defineContentContainer({ access })` from `@vitnode/core/content`:
| Value | Behavior |
| ------------------------ | ------------------------------------------------------------------------- |
| omitted or `false` | No access rules. The collection behaves as before |
| `true` | Every container gets rules; every action starts open to everyone |
| `{ defaults }` | Same, with collection defaults for some actions |
`defaults` is a partial `Record`. Role ids belong to one installation, so roles are chosen only in the AdminCP.
Content filed with a `field.container()` into the collection, and records under them (`container: true` relations, thread replies), follow the container's rules.
### Content type [#content-type]
`defineContentType({ access })` takes exactly one of:
| Value | Behavior |
| ---------------------------------- | --------------------------------------------------------------------------------------------- |
| `{ scope: true }` | Each record of this type is an access scope with its own rules, like a Blog category |
| `{ scope: { defaults } }` | Same, with defaults as above |
| `{ from: "" }` | Records are filed under the scope records the relation points at. Every one of them must allow the action |
`from` must name a shared (not localized) `field.relation()` whose target has `access: { scope }`. Anything else throws a `ContentEngineError` when the plugin loads.
## Actions and audiences [#actions-and-audiences]
| Action | Needs | Checked for |
| --------------------- | ------ | ------------------------------------------------------------------ |
| `view` | - | Containers in lists, trees and breadcrumbs; the scope's own page |
| `read` | `view` | Records: lists, detail, search, Discover, profiles, notifications |
| `comment` | `read` | Replies in a thread |
| `downloadAttachments` | `read` | Files other than images through the download route |
| Audience | Passes |
| ---------------------------------------- | -------------------------------------------------------------- |
| `{ mode: "everyone" }` | Guests and members |
| `{ mode: "members" }` | Signed-in members |
| `{ mode: "roles", roleIds: number[] }` | Members holding any of the roles, primary or secondary. Up to 100 roles |
Root roles follow the rules like any other role. An audience of roles lets a root role in only when its id is in `roleIds`. A rule whose roles were all deleted, or that cannot be read, lets nobody in. Stored rules are per scope and action; an action without one inherits from the nearest ancestor, then the defaults, then `everyone`.
The constants are exported from `@vitnode/core/content`: `CONTENT_ACCESS_ACTIONS`, `CONTENT_ACCESS_MODES`, `CONTENT_ACCESS_PREREQUISITES`, `CONTENT_ACCESS_MAX_ROLES` and `CONTENT_ACCESS_REQUIRED_CODE`.
## `createContentAccess` [#createcontentaccess]
`createContentAccess(c)` from `@vitnode/core/content/server` checks the current viewer inside a Hono route. Roles are read from the database once per request; the results are memoized for that request.
```ts title="plugins/forum/src/api/modules/forum/routes/show-topic-slug.route.ts"
import { createContentAccess } from "@vitnode/core/content/server";
const access = createContentAccess(c);
const [row] = await c
.get("db")
.select({ id: topics.id, slug: topics.slug })
.from(topics)
.where(
and(
eq(topics.id, id),
publicTopic(),
await access.condition(topicContent, "read"), // [!code highlight]
),
)
.limit(1);
if (!(await access.isOpen(topicContent))) {
return c.json(row, 200, { "Cache-Control": "private, no-store" });
}
```
| Method | Returns | Behavior |
| ---------------------------------------- | ---------------------------------------- | -------------------------------------------------------------------------------------------- |
| `actor()` | `ContentAccessActor` | `{ kind: "guest" }` or `{ kind: "member", userId, roleIds, system }`; `system` is `false` for every real member |
| `condition(model, action)` | `SQL \| undefined` | A `WHERE` condition keeping only rows the viewer may act on. `undefined` when nothing is restricted |
| `canRecord(model, id, action)` | `boolean` | One record, from its current scopes. A missing record is `false` |
| `canScope(familyId, scopeId, action)` | `boolean` | One container or scope record. An unknown scope is `false` |
| `flags(model, ids)` | `Map` | The four flags per record |
| `allowedScopes(familyId, action)` | `{ all: boolean; ids: string[] }` | The scopes of a family that allow the action. `all` when every scope does |
| `isOpen(model)` | `boolean` | `true` when no rule restricts anything in the model's family: the response may be shared |
| `scopesFor(model, values)` | `ContentAccessScopeRef[] \| null` | The scopes a record would be in with these values, before it is saved |
`model` is the content model from `createContentModel`. Records of a model without access are always allowed. Put `condition` in the query before `limit` and `offset`, so pages and counts never include what the viewer may not read.
Lower-level helpers are exported from the same path for plugin authors who build their own scope checks: `contentAccessCondition`, `canAccessContentRecord`, `contentRecordAccessFlags`, `decideContentAccessForScopes`, `contentAccessFlagsForScopes`, `contentAccessRequirementsForScopes`, `contentRecordAccessScopes`, `contentAccessAllowedScopes`, `isContentAccessOpen`, `resolveContentAccessActor` and `expireContentAccessFamily`.
## Response fields [#response-fields]
### Access flags [#access-flags]
```ts
interface ContentAccessFlags {
canView: boolean;
canRead: boolean;
canComment: boolean;
canDownloadAttachments: boolean;
}
```
- Every record of the public container routes carries `access: ContentAccessFlags`. Collections without access answer every flag `true`.
- `GET /permissions` of a content type adds the four flags to each record it returns, and leaves out records the viewer may not read.
Flags tell the UI what to offer. The server checks again on every request.
### Access required [#access-required]
A detail route answers `404` when the record is in a scope the viewer may not see, and `403` with this body when the viewer may see the scope but not read it:
```json title="GET /api/@vitnode/forum/content/topics/42 → 403"
{ "accessRequired": true, "code": "CONTENT_ACCESS_REQUIRED" }
```
The body never holds the record. Render it with `ContentAccessRequired` from `@vitnode/core/tanstack/content`:
| Prop | Type | Default | Description |
| -------------- | ---------------------------- | -------- | ------------------------------------------------- |
| `kind` | `"read"` \| `"comment"` | `"read"` | What is locked: the page, or replying |
| `headingLevel` | `"h1"` \| `"h2"` \| `"h3"` | `"h1"` | The title's level |
| `children` | `ReactNode` | - | Rendered under the message, such as a link back |
Guests get a sign-in link that returns to the page. Members get the message only.
### Download route [#download-route]
`GET /api/{pluginId}/content/{publicApi.path}/{id}/files/{fileId}` is mounted for every content type with access rules. It answers `200` with the file, `403` when the viewer may read the record but not download attachments, and `404` otherwise. See [Protected attachments](/docs/content-engine/access-attachments).
## AdminCP routes [#admincp-routes]
Mounted under the scope family's admin module, `/api/{pluginId}/admin/content/{admin.permissionModule}`. For Forum that is `/api/@vitnode/forum/admin/content/forum_forums`; for Blog categories `/api/@vitnode/blog/admin/content/categories`.
| Route | Permission | Behavior |
| ---------------------------------- | ---------- | ---------------------------------------------------------------------------------------- |
| `GET /{id}/access` | `can_view` | The scope's report: own rules, inherited rules and their source, every requirement, warnings, descendants. `roles` lists every role a rule can name (all but the guest role) |
| `POST /{id}/access/preview` | `can_view` | The same report for `{ overrides }` without saving |
| `PUT /{id}/access` | `can_edit` | Replaces the scope's rules with `{ overrides }` and expires the family's caches |
| `GET /access/files` | `can_view` | `{ privateStorage, private, public }`: the family's files by visibility |
| `POST /access/files/protect` | `can_edit` | Moves up to 100 public files to private storage: `{ moved, remaining, shared }` |
A content type filed under scopes gets `POST /access/effective` in its own module, such as `/api/@vitnode/blog/admin/content/posts/access/effective`. It takes `{ scopeIds }` (up to 50) and answers what readers need for each action across all of them, plus `missing` scope ids. `ContentAccessEffectiveNotice` from `@vitnode/core/views/admin/views/access/effective-notice` renders it in an editor as a **Public** or **Restricted** badge; click it for who can view, read, comment and download.
`overrides` is a partial `Record`. An action left out inherits. Call these routes with `rawFetcher`:
```ts
import { rawFetcher } from "@vitnode/core/tanstack/fetcher";
await rawFetcher({
method: "put",
pluginId: "@vitnode/forum",
prefixPath: "/admin",
module: "content/forum_forums",
path: "/3/access",
body: { overrides: { read: { mode: "roles", roleIds: [4] } } },
});
```
### Errors [#errors]
The routes answer `{ code, message }`:
| Status | `code` | When |
| ------ | -------------------- | ----------------------------------------------------------------------- |
| `400` | `invalidAccess` | The body does not match the schema, such as `roles` with no `roleIds` |
| `400` | `unknownRole` | A role does not exist, or is the guest role |
| `400` | `unsupportedStorage` | A `downloadAttachments` rule other than `everyone`, or protecting files, without a private store |
| `404` | `notFound` | No such scope, or the type has no access rules |
## Activity Logs and event [#activity-logs-and-event]
Every save that changes a rule records `content.access_updated` in
**AdminCP → Staff → Administrators → Logs**, in the same transaction as the
rules, with the old and new rule of each changed action. **Protect public
files** records `content.access_files_protected` with the counts it returned.
See [Activity logs](/docs/content-engine/activity-logs#access-rules).
`PUT /{id}/access` also emits `content.access.updated` after saving:
```ts title="plugins/site-notes/src/api/lib/access.listener.ts"
import { buildEventListener } from "@vitnode/core/api/lib/events";
export const accessListener = buildEventListener({
event: "content.access.updated",
name: "log-access-change",
handler: async (c, { changedActions, family, scopeId, userId }) => {
await c
.get("log")
.debug(`${family}:${scopeId} ${changedActions.join(", ")} by ${userId}`);
},
});
```
See [Built-in events](/docs/dev/events/built-in-events#content-access-events).
## Private storage store [#private-storage-store]
A storage adapter opts into private files with `private` on its `StorageApiPlugin`:
```ts
interface StoragePrivateStore {
upload: (args: StorageUploadArgs) => Promise<{ key: string }>;
read: (key: string) => Promise; size?: number }>;
delete: (key: string) => Promise;
}
```
Objects in it have no URL; VitNode serves them only through routes that check the viewer. Leave `private` out when the adapter cannot guarantee that nothing public reaches it. The Local adapter, and S3 or Supabase with `privateBucket`, provide one.
## Related [#related]
- [How access is enforced](/docs/content-engine/access-behavior)
- [Protected attachments](/docs/content-engine/access-attachments)
# Protected attachments (/docs/content-engine/access-attachments)
A rule on **Download attachments** only protects files nobody can fetch by URL. This guide sets up private storage, so files of access-controlled content are served only through a route that checks the reader every time, and moves the files that are still public.
## How files are served [#how-files-are-served]
Every content type with access rules gets a download route, `GET /api/{plugin}/content/{publicApi.path}/{id}/files/{fileId}`. It answers only when:
1. the reader may **read** the record, under its scopes' rules now;
2. the file belongs to that record: a file field holds it, or one of its rich-text documents names it;
3. for anything but an image, the reader may also **download attachments**.
Images follow **Read**: anyone who can read an article sees its images, and anyone who can see an image can save a copy of it. **Download attachments** covers files offered for download, such as PDFs and archives. A reader without it sees **An attachment is available. You do not have permission to download it.**, with no name, size or link:
File fields work the same way, with `restricted: true` on the descriptor.
Responses are `private, no-store`, `nosniff` and sandboxed. Nothing is served through a signed URL, so taking a role away blocks the next download at once.
## Before you begin [#before-you-begin]
You need [access rules](/docs/content-engine/access) on a container collection or a [scope content type](/docs/content-engine/access-categories), and a storage adapter.
### Give the storage adapter a private store [#give-the-storage-adapter-a-private-store]
The Local adapter keeps private files in `storage/private` in the API's working directory, which no static mount serves. It needs no configuration; do not serve that folder.
For S3 or Cloudflare R2, create a second bucket that is **not** public - no public bucket policy, no public R2 domain, no CDN in front of it - and pass it as `privateBucket`:
```ts title="apps/api/src/vitnode.api.config.ts"
import { S3StorageAdapter } from "@vitnode/s3";
storage: {
adapter: S3StorageAdapter({
accessKeyId: process.env.S3_ACCESS_KEY_ID,
bucket: process.env.S3_BUCKET,
privateBucket: process.env.S3_PRIVATE_BUCKET, // [!code ++]
region: process.env.S3_REGION,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
}),
},
```
`SupabaseStorageAdapter` takes `privateBucket` the same way; create that bucket as private in Supabase.
Without a private store, the AdminCP refuses a **Download attachments** rule other than **Everyone** and says why.
### Upload new files privately [#upload-new-files-privately]
Nothing to change in code. Once a content type has access rules and the adapter has a private store, its uploads are stored privately: file fields uploaded in the AdminCP, and rich-text uploads from editors that pass the content type, such as the Blog article editor.
To pass it from your own editor field:
```tsx title="plugins/blog/src/views/admin/article/editor-field.tsx"
```
The generated AdminCP form does this for every rich-text field with `uploads`.
### Move the files that are still public [#move-the-files-that-are-still-public]
Files uploaded before you set this up keep their public addresses. Open the **Access** dialog of any forum or category in the collection. If some of the collection's files still have a public address, the dialog says how many. Choose **Make N private** to move up to 100 of them into the private store; run it again until the notice is gone.
Moving a file deletes its public object, so the address handed out before stops working. A file that content outside the collection also uses stays public, and the result counts it as **used elsewhere** - a private reference cannot make a shared public file confidential, so upload it again where it should be private. Nothing private is ever made public.
## Check the result [#check-the-result]
Restrict **Download attachments** of a forum or category to a role, then attach a PDF to an article in it. As a member without the role, the article shows the attachment note instead of the file, and the download route answers `403`. With the role, the file downloads. Copy the download address, sign out and open it: the route answers `404`, because a guest cannot read the article.
## Related [#related]
- [Access rules](/docs/content-engine/access)
- [How access is enforced](/docs/content-engine/access-behavior)
- [Storage](/docs/dev/storage)
# How access is enforced (/docs/content-engine/access-behavior)
Access rules are enforced on the server, on every request, from the current rules, the current scope tree and the reader's current roles. This page explains where they apply, so you can predict what a member sees and debug when it is not what you expected.
## How a decision is made [#how-a-decision-is-made]
For one scope and one action, the server collects every requirement and lets the reader in only when all of them pass:
- the scope's own rule for the action and for each action it needs (**Read** needs **View**);
- the **View** rule of every ancestor, because a container inside a hidden one is hidden;
- for **Read** and what needs it, the **Read** rule of every ancestor, because a child can be stricter than its parent but never more open.
A rule left on **Inherit** comes from the nearest ancestor that sets it, then the collection's `defaults`, then **Everyone**. A record filed under several scopes, such as an article in two categories, needs every scope's requirements. Comments and replies follow their parent record.
Roles are read from the database for each request, never from a cached session. Taking a role away, moving a container under a restricted parent or changing a rule applies from the next request, including to forms a member already has open.
## Where the rules apply [#where-the-rules-apply]
| Path | Behavior |
| -------------------------------------- | ---------------------------------------------------------------------------------------------- |
| Public lists, detail, thread, delivery | Records the reader may not read are left out before pagination, so pages, cursors and totals never count them |
| Detail of a record in a hidden scope | `404`, the same as a record that never existed |
| Detail in a scope the reader may see | `403` with `{ accessRequired: true, code: "CONTENT_ACCESS_REQUIRED" }` and nothing else |
| Container list and detail | Hidden containers are left out, children included; every container carries `access` flags |
| Writes, edits, hide, delete, reports | Checked again on the server: a reply needs **Comment**, anything else **Read** |
| `GET /permissions` | Leaves out records the reader may not read; adds `canView`, `canRead`, `canComment`, `canDownloadAttachments` |
| Sitemaps | Only what a guest may read, in every language |
| Notifications and emails | Each recipient must be able to read the record when it is sent and every time the inbox loads |
Staff permissions grant nothing here. A moderator reads a restricted forum on the public site only when an access rule lets one of their roles in; give your moderator role access explicitly. The same goes for a **root role**. Tick it in the **Access** dialog wherever it should get in. The AdminCP and ModCP are staff areas behind their own permissions, so moderators keep reviewing reports and approvals there. A pending approval follows its record to its new container when the record moves, so it reaches that container's moderators.
Preview links are signed by staff for one revision. They show that revision whatever its scope's rules, as before, but protected files inside it still need a reader the rules let in.
## Search and Discover [#search-and-discover]
Search, suggestions, Discover, popular items, facets, author lists and profile timelines all use the same rules, with every supported adapter:
1. Each search document stores the scopes its record is filed in, such as `forum.forums:12` or `blog.category:3`. They are read from the content tables whenever the document is written.
2. A query keeps only documents whose every scope the reader may read. Postgres compares arrays; Elasticsearch uses a `terms_set` query.
3. Each result is checked against the content tables before it is returned. A document indexed before its record moved into a restricted scope is dropped, re-stamped, and left out of the total.
The index never grants access on its own. While a stale document waits for its fix, totals are an upper bound that never includes a result the reader was shown. An hourly job, `content-search-access`, re-stamps any document that drifted, so failed or delayed indexing heals without a rebuild.
## Caching [#caching]
A response is cached for everybody only when no access rule can change it: the family has no restriction at all. As soon as one forum or category is restricted, every response that depends on the reader is sent `private, no-store`, skips the API's shared public-read cache and stays out of the page cache. Pages for guests and members are then rendered per request.
Changing a rule, moving or deleting a container expires every cache the family decides: shared pages (hard), cached public reads, the container tree and sitemaps. Signing in, signing out or switching accounts clears the browser's cached queries, except translations.
External search engines may keep showing pages they crawled while they were public. Making a scope private removes it from your sitemap and makes its pages answer `404` or `403`; ask the search engine to recrawl or remove the URLs if it matters.
## Troubleshooting [#troubleshooting]
**Who changed a rule, and when?** Open **AdminCP → Staff → Administrators → Logs** and filter by **Changed access rules**. Each entry names the forum or category and shows the rule before and after.
**A member cannot see a forum they should.** Open the forum's **Access** dialog and find a role the member holds. An orange lock beside a ticked box means another rule still keeps that group out, often one on a parent forum. Hover the lock to see which. A **Read** rule on a parent hides every child's topics, even when the child is open.
**Nobody can open a forum.** A rule whose ticked roles were all deleted lets nobody in; the **Access** dialog warns about it. Deleting a role removes it from every rule, so a restricted scope stays restricted instead of opening up. Pick the roles again, or choose another audience.
**Attachments still download for everyone.** The files are probably still public. See [Protected attachments](/docs/content-engine/access-attachments#move-the-files-that-are-still-public).
**A custom route shows restricted content.** A plugin route that queries content tables directly ignores the rules. Read through the public service, or add `await createContentAccess(c).condition(model, "read")` to its `where`. See the [Access rules API](/docs/content-engine/access-api#createcontentaccess).
## Related [#related]
- [Access rules](/docs/content-engine/access)
- [Access rules API](/docs/content-engine/access-api)
# Category access (/docs/content-engine/access-categories)
A content type can hold access scopes of its own: every record gets view, read, comment and download rules, like a forum does. The Blog plugin uses this for categories, and an article is readable only when **every** one of its categories allows it.
Use it when the scopes are records you already manage in the AdminCP, such as categories or tags, rather than a [container tree](/docs/content-engine/access). The actions, audiences and prerequisites are the same as for containers.
## Before you begin [#before-you-begin]
You need a content type for the scopes and one filed under them through a relation. In the Blog plugin these are `blog.category` and `blog.post`, whose `categoryId` is a to-many relation to categories.
### Make each category a scope [#make-each-category-a-scope]
Add `access: { scope: true }` to the scope content type:
```ts title="plugins/blog/src/content/category.ts"
export const blogCategoryContentType = defineContentType({
id: "blog.category",
tableName: "blog_categories",
access: { scope: true }, // [!code ++]
// localization, fields and admin stay as they are
});
```
Every action starts open to everyone. `{ scope: { defaults: { comment: { mode: "members" } } } }` starts one stricter for every category.
### File articles under their categories [#file-articles-under-their-categories]
Point the article's `access.from` at the relation:
```ts title="plugins/blog/src/content/post.ts"
export const blogPostContentType = defineContentType({
id: "blog.post",
tableName: "blog_posts",
publication: true,
access: { from: "categoryId" }, // [!code ++]
fields: {
categoryId: field.relation({
min: 1,
multiple: true,
onDelete: "restrict",
target: () => blogCategoryContentType,
}),
// the other fields stay as they are
},
});
```
Comments need nothing: a record that answers a parent through its thread root, like `blog.comment` under its `article`, follows the parent's access.
### Restrict a category [#restrict-a-category]
Open **AdminCP → Categories** (`/admin/content/blog/categories`). In a category's row, choose **Access** (the lock button beside **Edit**). Turn off **Inherit** under **Read**, untick **Guests** and **Signed-in members**, then open **Roles** and leave only the role you want ticked. Choose **Save access**.
The article editor shows **Who can see this** under the categories field. It asks the server what the selected categories require together, so it is right before you save.
## How several categories combine [#how-several-categories-combine]
An article needs **all** of its categories' rules. Inside one category, a member with **any** of the ticked roles gets in; across categories, the rules add up:
| Category A | Category B | Who can read the article |
| ------------- | ------------- | --------------------------------------- |
| Everyone | Everyone | Everyone |
| Everyone | VIP | Members with VIP |
| VIP | Staff | Members with both VIP and Staff |
| VIP or Staff | Members | Signed-in members with VIP or Staff |
Adding a category can only narrow who reads an article, never widen it. The article editor warns about this under **Who can see this**.
A category a reader may not see is left out of the category list and its counts. An article they can read only ever names categories they can see, because reading it needs every one of them.
## Check the result [#check-the-result]
Create two categories, "News" (open) and "Insiders" (**Read**: a role). Publish one article in "News" and one in both. Signed out, `/blog` lists only the first; `/blog/category/insiders` asks you to sign in, and the second article's address does too. Signed in with the role, both articles show, and their comments work as before. Search for the second article's title in both states: only the member with the role finds it.
## Related [#related]
- [Access rules](/docs/content-engine/access)
- [Protected attachments](/docs/content-engine/access-attachments)
- [Access rules API](/docs/content-engine/access-api)
# Access rules (/docs/content-engine/access)
Access rules decide who may see a container, read what is filed in it, reply there and download its attachments. Use them for a staff-only forum, a members-only board, or a VIP section that only some roles can open.
This guide uses the Forum plugin: the `forum.forums` collection, topics filed into forums and comments that follow their topic.
## The four actions [#the-four-actions]
Each container has one rule per action. An action needs the one above it, so a role allowed to comment but not to read still cannot comment.
| Action | What it allows | Needs |
| ------------------------ | --------------------------------------------------------------------------- | ------ |
| **View** | See that the forum exists: its name and description in lists and breadcrumbs | - |
| **Read** | Open its topics, find them in search, Discover and profiles | View |
| **Comment** | Reply to its topics | Read |
| **Download attachments** | Download protected files attached to what the reader can read | Read |
Each rule lets in one of three audiences: everyone (**Guests** too), **Signed-in members** only, or only members holding at least one of the ticked **Roles**, as a primary or secondary role. Root roles such as Administrator get no special pass. They are rows like any other, so untick them to keep them out. Access rules only add restrictions. Replying still needs a signed-in member and the forum's [publishing rules](/docs/content-engine/container-policies), whatever **Comment** says.
## Before you begin [#before-you-begin]
You need a [container collection](/docs/content-engine/containers) with content filed into it. After upgrading VitNode, apply the migration that adds the access tables:
```bash tab="bun"
bun vitnode db migrate
```
```bash tab="pnpm"
pnpm vitnode db migrate
```
```bash tab="npm"
npx vitnode db migrate
```
### Turn on access for the collection [#turn-on-access-for-the-collection]
Add `access` to the collection's definition:
```ts title="plugins/forum/src/content/forums.ts"
import { defineContentContainer, field } from "@vitnode/core/content";
export const forumContainers = defineContentContainer({
id: "forum.forums",
fields: {
description: field.textarea({ maxLength: 500, nullable: true }),
},
hierarchy: { maxDepth: 4 },
access: true, // [!code ++]
publicApi: { path: "forums", fields: ["description"] },
admin: { path: "forum/forums" },
});
```
`access: true` starts every action open to everyone, so nothing changes until an administrator restricts a forum. To start stricter, pass defaults instead, such as `access: { defaults: { comment: { mode: "members" } } }`.
Turn access on only when every custom route of the plugin that reads topics or comments goes through the Content Engine's public services or `createContentAccess(c)`. A route that queries the table directly ignores the rules. The Forum plugin's stats and topic routes already do this.
### Restrict a forum in the AdminCP [#restrict-a-forum-in-the-admincp]
Open **AdminCP → Forums** (`/admin/containers/forum/forums`). In a forum's row menu, choose **Access**.
The **Access** dialog is a grid: groups down the side (**Guests**, **Signed-in members** and **Roles**, which opens into every role), the four actions across the top. For a forum called "Members", turn off **Inherit** under **View**, untick **Guests** and choose **Save access**.
An action left on **Inherit** follows the nearest parent forum that sets it, then the collection's defaults. The caption under its switch shows the inherited audience and where it comes from, such as **Everyone** and **no rule above**. An orange lock beside a ticked box means another rule still keeps that group out. Hover or focus the lock to see which one. In the screenshot, guests are still ticked for **Read**, but a lock sits beside each box. Guests cannot read a forum they cannot view.
Saving needs the collection's `can_edit` admin permission. The rules apply from the next request, including to members who are signed in right now.
### Restrict a child forum to a role [#restrict-a-child-forum-to-a-role]
Under "Members", create a forum called "VIP". Open its **Access** dialog and turn off **Inherit** under **View**. Untick **Guests** and **Signed-in members**, which leaves every role ticked. Open **Roles**, untick the **Roles** row to clear them, tick **VIP** and save.
A child can be stricter than its parent, never more open: to reach "VIP", a member has to pass the rules of "Members" too. The locks show this. "Members" keeps guests out, and every role except VIP needs **View** first:
With "General" left on **Inherit** beside it:
| Visitor | Members | General | VIP |
| ----------------------------- | ------- | ------- | --- |
| Guest | No | No | No |
| Member without the VIP role | Yes | Yes | No |
| Member with the VIP role | Yes | Yes | Yes |
## Check the result [#check-the-result]
Sign out and open `/forum`. "Members" and its children are gone from the forum list, and `/forum/members` answers **Forum not found**, as if it never existed. Sign in as a member without the VIP role: "Members" and "General" appear, "VIP" does not. Search for a topic title from "VIP" as both visitors: only a member with the role finds it.
To try a forum readers may see but not read, set **View** to **Everyone** and **Read** to **Signed-in members**. Guests then see the forum with a **Restricted** label:
Its page and its topics ask guests to sign in instead of showing anything. A signed-in member without access sees **You don't have access here** instead.
## Related [#related]
- [Blog category access](/docs/content-engine/access-categories)
- [Protected attachments](/docs/content-engine/access-attachments)
- [How access is enforced](/docs/content-engine/access-behavior)
# Activity logs (/docs/content-engine/activity-logs)
Every content type is audited out of the box, no code required. Creating,
editing, deleting, duplicating, publishing, hiding, restoring, scheduling and
every translation change land in the [Activity Logs](/docs/dev/audit-logs) with
the actor, the record, the changed fields and, for an editorial content type,
the revision it created. This page covers what gets recorded and how to tune it.
## What an entry contains [#what-an-entry-contains]
| Field | Value |
| -------------- | --------------------------------------------------------------------------------------------------------------------- |
| Plugin | The content type's plugin, from the content registry, never from the request |
| Action | `content.created`, `content.updated`, `content.translation_published`... |
| Target | The content type id (`blog.category`), the record id and its title at the time |
| Changed fields | The canonical paths the write moved (`seo.title`, `categories`) |
| Changes | Without `editorial`: bounded before/after values of the changed scalar fields. With it: none, the revision holds them |
| Revision | The revision the write created, shown as a diff against the previous one |
| Locale | For translation operations |
Delivery events (`delivery_slug_changed`, `delivery_redirect_created`) do not
get entries of their own. The slug change is part of the `content.updated`
entry. The area follows the request: `admin` from the AdminCP, `public` for a member's own
write, `moderator` from a report or approval, `system` for scheduled work.
## Why entries are written in the transaction [#why-entries-are-written-in-the-transaction]
Content events fire after a write commits, which is too late for a listener to
keep the audit trail atomic. So the Content Engine writes the entry **inside**
the write's transaction: beside the revision for an editorial content type, and
in the plain service's transaction otherwise. A rolled-back write leaves no entry,
and a write whose entry cannot be stored does not commit.
This holds for the generated AdminCP routes, the public write API, approvals,
moderation actions and your own code calling `model.service(c)` or
`model.editorialService(c)`, because they all go through the same services.
## One operation, one entry [#one-operation-one-entry]
Some operations write more than one thing. The Content Engine records the
operation the person asked for:
| Operation | Entries |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Create a localized record with its translations | One `content.created`, labelled with the default translation's title, listing the locales |
| Publish a localized record | One `content.published` listing the languages it published |
| Duplicate a record | One `content.duplicated` on the copy, with the source id |
| Save shared fields and a translation together | One entry per part that moved, sharing a request id |
## Access rules [#access-rules]
Saving a forum's or a category's [access rules](/docs/content-engine/access)
records `content.access_updated` under the plugin that owns them, labelled
with the forum or category name. Its changes hold the old and new rule of each
action that moved, as `inherit`, `everyone`, `members` or `roles: VIP, Staff`
with the role names of that moment. A save that changes nothing records
nothing, and a save that fails leaves no entry.
**Make N private** in the **Access** dialog records `content.access_files_protected` with how
many files moved, how many other content still uses and how many are left.
## Scheduled publishing [#scheduled-publishing]
The system runs a scheduled publish or unpublish, so its entry has the
**System** actor and `area: system`. Whoever booked it travels in the metadata:
```json
{
"action": "content.published",
"actorType": "system",
"metadata": {
"scheduledByUserId": 12,
"scheduleId": 40,
"trigger": "scheduled_task"
}
}
```
Booking and cancelling the schedule are entries of their own
(`content.scheduled`, `content.schedule_cancelled`) attributed to the admin.
The execution runs in the schedule's claim transaction, so a retried run never
records twice.
## Tune or disable it [#tune-or-disable-it]
Auditing is on by default. Pass `audit` to `defineContentType` to keep noisy
fields out of the recorded changes, or `false` to turn it off.
```ts title="plugins/shop/src/content/product.ts"
import { defineContentType, field } from '@vitnode/core/content'
export const productContentType = defineContentType({
id: 'shop.product',
tableName: 'shop_products',
fields: {
name: field.text({ required: true, maxLength: 200 }),
stock: field.number({ integer: true, required: true }),
},
// Stock moves with every order; the entry still says the product changed.
audit: { excludeFields: ['stock'] }, // [!code ++]
})
```
| Option | Type | Default | Description |
| --------------- | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `excludeFields` | field names | `[]` | Never named or diffed in an entry; a group name covers its nested fields. The write itself is still recorded. An unknown field name throws when the content type is defined. |
| `trackChanges` | `boolean` | `true` | `false` records the operation only, without changed fields or values. |
`audit: false` records nothing for the content type. Use it only for
high-volume, non-sensitive content. Sensitive field names (passwords, tokens,
secrets, API keys) are redacted no matter what you set here.
## See a record's history in the AdminCP [#see-a-records-history-in-the-admincp]
Every content list has an **Activity** row action for admins with `can_view`
on the content type. It opens the record's entries, newest first, with their
changes, for any content type, editorial or not. Don't mix it up with
**History**, which shows what the content itself used to be.
To show the same history on your own AdminCP screen, render `ActivityHistory`
inside `RouteMessages` with the Activity Logs messages and your plugin's
content labels:
```tsx title="plugins/blog/src/views/admin/category-activity.tsx"
import { RouteMessages } from '@vitnode/core/tanstack/i18n'
import { ActivityHistory } from '@vitnode/core/views/activity-logs/activity-history'
export const CategoryActivity = ({ categoryId }: { categoryId: number }) => (
)
```
`ActivityHistory` reads `GET /admin/activity-logs/entity`, so it shows entries
only to admins allowed to read that record's history. `RouteMessages` suspends
while the messages load, so render it inside a `Suspense` boundary with a
skeleton fallback.
## Related [#related]
- [Activity Logs](/docs/dev/audit-logs): where staff read every entry
- [Record plugin events](/docs/dev/audit-logs/record-plugin-events): audit your plugin's own tables
- [Revisions](/docs/content-engine/editorial): what a record used to be, and the History panel
# AdminCP (/docs/content-engine/admincp)
Every content type registered in the plugin's `src/admin/content.tsx` gets an AdminCP list and a create and edit form without any UI code. Most changes are options in the definition's `admin` block. For anything the options cannot express, you swap one cell, one field or the whole form layout for your own component.
This page uses the newsroom plugin's `newsroom.story`. Its screen lives at `/admin/content/newsroom/stories`.
## Choose list columns, search and sorting [#choose-list-columns-search-and-sorting]
`admin.list` drives the list:
```ts title="plugins/newsroom/src/content/story.ts"
admin: {
path: "newsroom/stories",
titleField: "title",
list: {
columns: [
"status",
"title",
"slug",
"code",
"category",
"author",
"animation",
"publishedAt",
"updatedAt",
],
searchableFields: ["title", "code", "excerpt"],
orderableFields: ["title", "code", "slug"],
defaultOrderBy: "updatedAt",
defaultOrder: "desc",
},
},
```
| Option | What it does |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `columns` | Table columns, in order. The default is `status` (with publication), every shared single-value field, then `updatedAt`. |
| `searchableFields` | Fields the search box matches: `text`, `textarea`, `slug` or `richText`. A localized field matches in any language. The default is every shared text and textarea field. When the list ends up empty, the search box is hidden. |
| `orderableFields` | Your own fields with a sortable header. `id`, `createdAt` and `updatedAt` are always sortable, and so are `status`, `publishedAt` (with publication) and `version` (with editorial), so leave them out. Localized and file fields cannot be sorted. |
| `defaultOrderBy` | Initial sort column. Must be a built-in column or one of `orderableFields`. Defaults to `updatedAt`. |
| `defaultOrder` | `"asc"` or `"desc"`. Defaults to `"desc"`. |
| `thumbnailField` | A single shared `field.file()` drawn at the start of the title cell. `titleField` must be one of the `columns`. |
A to-many `field.user()` or `field.relation()` can be a column. People show with their role color and relations as badges, loaded once per page instead of once per row. A gallery (`field.file({ multiple: true })`), a group or a repeatable cannot. A file column shows a thumbnail and the file name, which is why `animation` above is a column but not sortable.
Every mistake here, such as an unknown field or a gallery in `columns`, throws a `ContentEngineError` when the plugin loads, so you find it before an editor does.
### Other `admin` options [#other-admin-options]
| Option | Default | What it does |
| ------------------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `path` | The id with dots as slashes | URL under `/admin/content/`. Lowercase segments of letters, digits and dashes; cannot end in `create` or `edit`. |
| `titleField` | First shared text or textarea field | Names a record in toasts, dialogs and relation pickers. `null` means the type has no title. |
| `colorField` | none | A shared field with a color, shown as a swatch next to the title. The blog's categories use it. |
| `navigation` | `true` | Set it to `false` to keep the screen but drop its sidebar link. |
| `permissionModule` | The id without the plugin part | Staff permission module name, for example `story` for `newsroom.story`. |
## Bulk actions [#bulk-actions]
Ticking rows opens a floating bar with two menus and a **Delete** button. **Status** holds Publish and Unpublish, **Visibility** holds Hide and Unhide. Each option says how many of the ticked rows it applies to, such as **2 of 3**, and only those rows change: hiding two visible articles and one already hidden sends two requests, not three. An option that fits none of them is greyed out.
There is nothing to configure. **Status** appears with `publication` and the `can_publish` permission, **Visibility** with [`visibility`](/docs/content-engine/content-visibility) and `can_hide`, **Delete** with `can_delete`. Without any of them, the table has no checkboxes. On a phone the bar shrinks to icons.
Each action asks for confirmation and then sends one request per record to the same route the row buttons use, so events, search indexing and revisions behave as if you clicked every row. When some records fail, for example because someone else saved them meanwhile, the rest still go through. A toast says how many were skipped, and those rows stay ticked.
## Duplicate and hide records [#duplicate-and-hide-records]
The **More actions** menu of each row collects the less frequent actions. On a type whose records have [access rules](/docs/content-engine/access-categories), such as blog categories, **Access** stays a button beside **Edit**, and **Activity** and **Delete** move into the menu. Two of the menu's actions come from options in the definition:
- **Duplicate** appears with [`duplication`](/docs/content-engine/duplicate-content), for staff with `can_create` and `can_view`. It makes a draft copy and opens it.
- **Hide** or **Unhide** appears with [`visibility`](/docs/content-engine/content-visibility), for staff with `can_hide`. A hidden record gets an eye-off icon before its title, with a tooltip such as **Article hidden**, and the toolbar gets a **Visibility** filter with **All**, **Visible** and **Hidden**.
Each action asks for confirmation, refreshes the list and shows a toast. On the edit page, `ContentFormActions` adds a **Hide** or **Unhide** button next to **Save changes**, and `ContentFormStatus` shows the same **Hidden** badge with a short explanation.
## Live updates [#live-updates]
Every generated list stays current while it's open, with no configuration. When a record of the same type changes in another tab or session, such as another admin's edit, a member's post or a scheduled publish, the page on screen reads again with its filters, search, sort and page. Selected rows that are still on the page stay ticked, and a burst of changes costs one read. If that read fails, the list keeps its rows and shows **Could not refresh this list** with **Try again**.
Live updates need the app to serve the [WebSocket](/docs/dev/websocket/setup). [Live refresh](/docs/content-engine/live-refresh) explains who receives what.
## Group form fields into sections [#group-form-fields-into-sections]
By default the form shows every field except `field.blocks()`, one after another, in a dialog:
To pick and order fields, set `admin.form.fields`. To group them into titled cards, use `admin.form.sections` instead. For the newsroom's stories, that could look like this:
```ts title="Example: story form sections"
admin: {
form: {
sections: [
{ name: "main", fields: ["title", "slug", "excerpt", "category"] },
{ name: "media", fields: ["animation", "gallery"] },
{ name: "settings", fields: ["code", "author", "featured", "noIndex", "views"] },
],
},
},
```
- Sections are the field list, so a field you leave out is not in the form. Declaring both `fields` and `sections` throws.
- Each field belongs to one section, and no section may be empty.
- A section `name` is lowercase snake case, because it is part of a translation key.
The heading and an optional description come from the plugin's locale file, at `content..form.`. Without a message, the heading is the humanized name ("Main").
```json title="Example: section headings in en.json"
{
"newsroom": {
"content": {
"story": {
"form": {
"main": { "title": "Story", "desc": "What readers see first." },
"media": { "title": "Media" }
}
}
}
}
}
```
## Open forms on their own page [#open-forms-on-their-own-page]
Forms open in a dialog. A short form, like the blog's categories (a name and a color), can slide in from the right instead with `create: { mode: "sheet" }` and `edit: { mode: "sheet" }`, so the list stays in view beside it. A long form reads better on a page, which is what the blog does for its articles:
```ts title="plugins/blog/src/content/post.ts"
admin: {
path: "blog/articles",
create: { mode: "page" },
edit: { mode: "page" },
},
```
The create form moves to `/admin/content/blog/articles/create` and the edit form to `/admin/content/blog/articles/{id}/edit`. You can set the two modes independently.
## Replace a field or a cell [#replace-a-field-or-a-cell]
Wrap a registration in `contentTypeAdmin` to swap the component of one form field or one list column. It adds nothing at runtime; it only checks that the keys are real field names. The blog plugin does this for its category color:
```tsx title="plugins/blog/src/admin/content.tsx"
import type { ContentFrontendPluginSource } from "@vitnode/core/lib/plugin";
import { contentTypeAdmin } from "@vitnode/core/lib/plugin";
import { manifest } from "@/manifest.gen";
import { BlogCategoryColorCell } from "@/views/admin/category/color-cell";
import { BlogCategoryColorField } from "@/views/admin/category/color-field";
import { blogCategoryNav } from "./nav";
export const adminContent = {
pluginId: manifest.id,
contentTypes: [
contentTypeAdmin({
...blogCategoryNav,
fields: {
color: { component: BlogCategoryColorField },
},
columns: {
color: { cell: BlogCategoryColorCell },
},
}),
],
} satisfies ContentFrontendPluginSource;
```
A cell receives the row, typed by the definition:
```tsx title="plugins/blog/src/views/admin/category/color-cell.tsx"
import type { ContentCellProps } from "@vitnode/core/lib/plugin";
import { useTranslations } from "use-intl";
import type { blogCategoryContentType } from "@/content/category";
export const BlogCategoryColorCell = ({
row,
}: ContentCellProps) => {
const t = useTranslations("@vitnode/blog.admin.category");
if (!row.color) {
return {t("color.none")};
}
return (
{row.color}
);
};
```
A field component receives `ItemAutoFormComponentProps` from `@vitnode/core/components/form/auto-form` and usually wraps an [AutoForm](/docs/ui/auto-form) field with your own label or control.
Add `skeleton` when the component is bigger than its field kind suggests, so the loading placeholder matches. The blog's `content` field renders a rich editor and sets `skeleton: "editor"`. The options are `"editor"`, `"input"`, `"list"`, `"media"`, `"switch"` and `"textarea"`.
## Replace the whole form layout [#replace-the-whole-form-layout]
For a layout the options cannot express, such as a main column with a sidebar, pass `forms.layout` to `contentTypeAdmin`. A custom layout is used only in page mode, so set `create.mode` and `edit.mode` to `"page"` first.
```tsx title="Example: a story form layout"
import type { ContentFormLayoutProps } from "@vitnode/core/lib/plugin";
import {
ContentFormActions,
ContentFormField,
ContentFormHeader,
ContentFormLayoutGrid,
ContentFormMain,
ContentFormRemainingFields,
ContentFormSection,
ContentFormSidebar,
ContentFormStatus,
} from "@vitnode/core/content/admin-form";
const SIDEBAR_FIELDS = ["category", "author", "featured", "noIndex"];
export const StoryFormLayout = ({ mode }: ContentFormLayoutProps) => (
<>
{mode === "edit" ? : null}
{SIDEBAR_FIELDS.map(name => (
))}
>
);
```
```tsx title="Example: register the layout in src/admin/content.tsx"
contentTypeAdmin({
definition: storyContentType,
icon: ,
forms: { layout: StoryFormLayout }, // [!code ++]
}),
```
`forms.create.layout` and `forms.edit.layout` override the shared one per action. For a content type with [`visibility`](/docs/content-engine/content-visibility), `ContentFormHiddenIcon`, `ContentFormHiddenNotice` and `ContentFormVisibilityToggle` from the same import place the icon, the explanation and the button yourself. The blog's editor puts `ContentFormHiddenIcon` before the title and `ContentFormHiddenNotice` under its header. For a one-row header, `ContentFormPublicationLabel` shows **Draft** or **Published** as plain text (hover it for the publish date), and `ContentFormSaveMenu` is **Save changes** with a ▾ menu holding **Publish** or **Unpublish** and **Hide** or **Unhide**, each behind the usual confirmation. `ContentFormRemainingFields` renders every form field you did not place yourself. In development, the browser console warns about fields the layout never rendered and about a missing `ContentFormHeader`, which holds the title and the back link.
## Show a matching skeleton [#show-a-matching-skeleton]
A loading screen that looks nothing like the form is the visual version of a
jump scare. The Content Engine avoids it by rendering your layout twice: first in
**skeleton mode** while the record loads, then for real. In skeleton mode,
`useContentForm().skeleton` is `true` and every ``
draws a placeholder instead of the field.
So a layout built only from `ContentFormField`, `ContentFormRemainingFields` and
the other `ContentForm*` pieces already has a matching skeleton. You only need
two extra steps when your form draws more than fields.
### Size a field's placeholder [#size-a-fields-placeholder]
Each placeholder is sized from the field's kind. When your field component is
bigger than its kind suggests, set `skeleton` next to `component`, as described
in [Replace a field or a cell](#replace-a-field-or-a-cell):
```tsx title="plugins/blog/src/admin/content.tsx"
fields: {
content: { component: BlogArticleEditorField, skeleton: "editor" },
excerpt: { component: ArticleExcerptField, skeleton: "textarea" },
},
```
### Draw a skeleton for a custom layout [#draw-a-skeleton-for-a-custom-layout]
A layout with its own header, a large title or a cover image should draw a
skeleton with the same wrappers, gaps and widths. Return it while `skeleton` is
`true`, and use the same component as the `Suspense` fallback when the real
editor is lazy-loaded. Then the reload goes skeleton → form with nothing in
between.
```tsx title="plugins/blog/src/views/admin/article/form-layout.tsx"
import type { ContentFormLayoutProps } from "@vitnode/core/lib/plugin";
import { Skeleton } from "@vitnode/core/components/ui/skeleton";
import { useContentForm } from "@vitnode/core/content/admin-form";
import React from "react";
const loadArticleEditor = async () => await import("./editor/article-editor");
const ArticleEditor = React.lazy(async () =>
loadArticleEditor().then(module => ({ default: module.ArticleEditor })),
);
const ArticleEditorSkeleton = () => {
const { fieldNames, markHeaderRendered, markRendered, mode, skeleton } =
useContentForm();
markHeaderRendered?.();
if (!skeleton) for (const name of fieldNames) markRendered?.(name);
React.useEffect(() => {
void loadArticleEditor();
}, []);
return (
{mode === "edit" ? (
) : (
)}
);
};
export const BlogArticleFormLayout = ({
contentTypeId,
itemId,
}: ContentFormLayoutProps) => {
const { skeleton } = useContentForm();
if (skeleton) return ;
return (
}>
);
};
```
A few things that keep it smooth:
- **Copy the real wrappers.** Same outer `div`, same padding, same `max-w-*`,
same breakpoints. A skeleton that is 20 pixels shorter still makes the page
jump.
- **Branch on `mode`.** The create form often looks different, for example an
empty upload area instead of a cover image and other buttons in the header.
- **Call `markHeaderRendered()`** when the skeleton draws its own header, so the
development warning about a missing `ContentFormHeader` stays quiet.
- **Mark the fields as rendered in the fallback.** While the lazy editor loads,
the real form is up, so the skeleton tells it that the layout will place every
field. Without it, the console warns about missing fields for a moment.
- **Start loading the editor from the skeleton.** The `useEffect` above fetches
the editor's code while the record is still loading, so the fallback is rarely
seen at all.
- **Use `Skeleton` from `@vitnode/core/components/ui/skeleton`** and the
Tailwind spacing scale, so placeholders match the theme in light and dark mode.
## Check the result [#check-the-result]
Save the definition and open **AdminCP → Newsroom → Stories**. `pnpm dev` reloads both the screens and the API, which validates sorting and form input against the same definition.
Next, give the screens the permissions they need in [Production checklist](/docs/content-engine/production), or read every option in the [reference](/docs/content-engine/reference).
# Approval notices (/docs/content-engine/approval-notices)
When a container's [publishing rules](/docs/content-engine/container-policies) hold edits for a moderator, a successful save does not mean the change is live. This guide adds what an author needs on the edit page: the form opens on their pending proposal, a notice says what is waiting or why it was declined, and the toast after a save tells the truth.
The example is the Forum plugin's edit page, `plugins/forum/src/pages/topic-edit-page.tsx`. The code below is excerpts from that file.
## Before you begin [#before-you-begin]
Approval only exists for records filed in a container whose definition has `policies`. Check that your content type has all three:
- **A container with policies.** The forum's `forumContainers` in `plugins/forum/src/content/forums.ts` sets `policies: { defaults: { ... } }`.
- **A record filed in it.** `forum.topic` has `forum: field.container({ definition: forumContainers, required: true })`. A comment can inherit its topic's forum with `field.relation({ target: () => topicContentType, container: true })`.
- **A rule that waits.** In the AdminCP, open `/admin/containers/forum/forums`, choose **Publishing** in a forum's row menu, set **Edits to published posts** to **Wait for approval** for topics and choose **Save rules**.
You also need an edit page that loads `GET /{id}/edit` and saves with `useContentPublicWrite`, like the [Edit form](/docs/content-engine/public-write-edit), and a member who is not a moderator in that forum. The excerpts use two names from such a page:
- **`EditableTopic`** is the record type the loader returns, `Extract["record"]`, declared like `EditableArticle` in [Load the editable values](/docs/content-engine/public-write-edit#load-the-editable-values).
- **`TopicFormValues`** is the values type of the shared form, exported from `plugins/forum/src/pages/topic-form.tsx` like `ArticleFormValues` from the article form.
The newsroom tutorial's articles are not filed in a container, so `approval` is always `null` for them. A content type without a container keeps its drafts as plain drafts, even with `create.status: "draft"`; see [Drafts and approval](/docs/content-engine/approvals#drafts-and-approval).
## Three kinds of values [#three-kinds-of-values]
With approval on, an edit page handles three different things. Keep them apart, or the author will think a change is live when it is not:
| What | Where it comes from | Readers see it |
| --- | --- | --- |
| **Live values** | `record.values` from `GET /{id}/edit` and `PATCH /{id}` | Yes |
| **Proposed values** | `record.approval.values`, when `approval.status` is `"pending"` and `approval.kind` is `"edit"` | No, until a moderator approves |
| **A save that waits** | `PATCH /{id}` answers `200` with `approval.status: "pending"`; `values` is still the live record | No |
### Open the form on the proposal [#open-the-form-on-the-proposal]
When the author reopens a page whose edit is pending, the form should show what they sent, not the live text. `approval.values` is untyped, so parse the fields the form knows and fall back to the live value for the rest:
```tsx title="plugins/forum/src/pages/topic-edit-page.tsx (excerpt)"
import { zodRichTextDocument } from "@vitnode/core/content";
import { z } from "zod";
import type { TopicFormValues } from "./topic-form";
const zodProposedValues = z
.object({
body: zodRichTextDocument.optional(),
title: z.string().optional(),
})
.catch({});
const formValuesOf = (record: EditableTopic): TopicFormValues => {
const { approval } = record;
const proposed =
approval?.status === "pending" && approval.kind === "edit"
? zodProposedValues.parse(approval.values ?? {})
: {};
return {
body: proposed.body ?? record.values.body,
title: proposed.title ?? record.values.title,
};
};
```
Use `formValuesOf(record)` wherever the basic edit form used `record.values` for its defaults.
### Show a notice from the server's answer [#show-a-notice-from-the-servers-answer]
`approval` is `null` when nothing waits. Otherwise it is a pending submission, or a rejected one nothing has replaced yet. The notice reads that object and nothing else:
```tsx title="plugins/forum/src/pages/topic-edit-page.tsx (excerpt)"
import type { ContentApprovalState } from "@vitnode/core/content";
import {
Alert,
AlertDescription,
AlertTitle,
} from "@vitnode/core/components/ui/alert";
import { HrefLink } from "@vitnode/core/tanstack/link";
import { HourglassIcon, XCircleIcon } from "lucide-react";
import { useTranslations } from "use-intl";
import { FORUM_PENDING_HREF } from "./forum-links";
/** Reads only the server's `approval`: neither the URL nor a draft status adds a notice. */
const ApprovalNotice = ({
approval,
}: {
/** Only what the notice reads, so the edit route's JSON answer fits as is. */
approval: null | Pick;
}) => {
const t = useTranslations("@vitnode/forum.topics.approval");
if (approval?.status === "rejected") {
return (
} variant="destructive">
{t("rejected.title")}
{approval.reason
? t("rejected.reason", { reason: approval.reason })
: t("rejected.desc")}
);
}
if (approval?.status === "pending" && approval.kind === "edit") {
return (
} variant="info">
{t("pending_edit.title")}{t("pending_edit.desc")}
);
}
if (approval?.status === "pending" && approval.kind === "create") {
return (
} variant="info">
{t("pending_create.title")}
{t("pending_create.desc")}{" "}
{t("pending_create.link")}
);
}
return null;
};
```
- **Rejected** shows the moderator's reason when there is one. The author can edit and save again, which opens a new submission.
- **Pending edit** needs `status: "pending"` and `kind: "edit"`, and says readers still see the published version.
- **Pending create** needs `status: "pending"` and `kind: "create"`, which means a new topic waits for its first approval. It links to the author's list of posts awaiting approval, `/forum/me/pending`.
- **Nothing else.** `approval: null` renders no notice, even for a draft. A draft is not a submission, so the notice never looks at `status`, and it never reads the URL.
The approval state comes from the server. The route's loader awaits `GET /{id}/edit` before the page renders, and its answer carries `approval`. Every save replaces it with the one `PATCH /{id}` returns.
### Keep the answer's state after a save [#keep-the-answers-state-after-a-save]
`PATCH /{id}` answers with the record's `approval`, `slug` and `status`. Keep them in state, so the notice and the **View topic** link follow every save, and pick the toast from `approval`:
```tsx title="plugins/forum/src/pages/topic-edit-page.tsx (excerpt)"
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { invalidateForumTopics } from "./forum-queries";
// Inside the form component, next to `useContentPublicWrite`:
const queryClient = useQueryClient();
const [current, setCurrent] = useState({
approval: record.approval,
slug: record.slug,
status: record.status,
});
const [defaults, setDefaults] = useState(() => formValuesOf(record));
// In onSubmit, after `const updated = await write.submit(...)`:
if (!updated) return;
setCurrent({
approval: updated.approval,
slug: updated.slug,
status: updated.status,
});
setDefaults(values);
form.reset(values);
await invalidateForumTopics(queryClient);
if (updated.approval?.status === "pending") {
toast.info(t("edit.pending.title"), { description: t("edit.pending.desc") });
} else {
toast.success(t("edit.success.title"), {
description: t("edit.success.desc", { title: values.title }),
});
}
```
Render `` above `{write.conflict}` and the form. `invalidateForumTopics` refreshes the forum's cached topic lists; in your plugin, invalidate your own list's query key, as the [Edit form](/docs/content-engine/public-write-edit#update-the-form-and-the-cached-lists) does. The server checks a proposal against the record's `version` like any edit, so the conflict alert keeps working.
### Add the labels [#add-the-labels]
The forum keeps the notice labels under `topics.approval` and the toast under `topics.edit` in `plugins/forum/src/locales/en.json`:
```json title="plugins/forum/src/locales/en.json (excerpt)"
{
"@vitnode/forum": {
"topics": {
"approval": {
"rejected": {
"title": "A moderator declined this",
"desc": "Your submission was not approved. You can edit it and send it again.",
"reason": "Reason: {reason}"
},
"pending_edit": {
"title": "Your changes are waiting for approval",
"desc": "Readers still see the published version. You are looking at your proposed changes."
},
"pending_create": {
"title": "Waiting for a moderator",
"desc": "Your topic goes live as soon as a moderator approves it. You can still polish it here.",
"link": "See all your posts awaiting approval."
}
},
"edit": {
"pending": {
"title": "Sent for approval",
"desc": "A moderator will review your changes. Readers see the published version until then."
},
"success": { "title": "Topic saved", "desc": "\"{title}\" is up to date." }
}
}
}
}
```
## Check the result [#check-the-result]
Sign in as a member who wrote a published topic in the forum that waits for edits, and open `/forum/topics/{id}/edit`.
1. Change the title and click **Save changes**. **Sent for approval** appears, the notice says your changes wait, and the form keeps your new title. The topic's public page still shows the old title.
2. Reload the edit page. The form opens on your proposal, not on the live title.
3. As a moderator with `can_approve` in that forum, reject the submission with a reason in the [ModCP](/docs/dev/moderation/review-approvals). Reload the author's edit page. The notice shows the reason, and the form shows the live text again.
4. Save another change and approve it instead. After a reload the notice is gone, and both the form and the public page show the new title.
5. Open a topic with nothing pending, then one that staff unpublished in the AdminCP, which is a draft with `approval: null`. Neither shows a notice, even with `?submitted=1` added to the URL. Older Forum links carried that flag, and the edit page now ignores it.
# Approvals (/docs/content-engine/approvals)
When a container's [publishing policy](/docs/content-engine/container-policies) says `publish: "approve"` or `edits: "approve"`, a member's post does not go live straight away. The server stores a **submission**, a moderator decides, and only an approval changes what readers see. This page explains what waits where, what the author sees, and what a decision does. The moderator's side is in [Review approvals](/docs/dev/moderation/review-approvals).
## What waits, and where [#what-waits-and-where]
The server decides from the effective policy of the record's container. The client never sends a status.
| The author | What is stored |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| Creates a topic in an `approve` forum | A `draft` row plus a `create` submission. Nothing public can reach a draft |
| Edits a published topic, with `edits: "approve"` | An `edit` submission holding the proposed values. The live row and its `version` do not change |
| Edits again while that proposal is pending | A new proposal. The old one becomes `superseded`, so a record never has more than one pending submission |
| Edits a draft whose create is pending | The draft is updated in place, and the pending submission follows it |
| Edits a draft whose create was rejected | The draft is updated, and a new `create` submission opens: a resubmission |
A proposal is validated like a normal edit before it is stored, so a moderator never reviews something that could not be saved.
## Drafts and approval [#drafts-and-approval]
A draft and a pending submission are different states. Check both `status` and `approval` in every write response:
| State | `status` | `approval` | Readers see it |
| --- | --- | --- | --- |
| **Published** | `"published"` | `null` | Yes |
| **Draft, nothing submitted** | `"draft"` | `null` | No, and no moderator is asked |
| **Pending approval** | `"draft"` for a new record, `"published"` for a pending edit | `{ status: "pending", ... }` | No, until a moderator approves |
| **Rejected** | unchanged | `{ status: "rejected", reason, ... }` | Only what was already published |
A submission only opens for a record filed in a container whose definition has `policies`, either through its own `field.container()` or a `field.relation({ container: true })` to a record that has one. In that case `publicWrite.create.status: "draft"` is the fallback for `publish: "approve"`. Without a container, `create.status: "draft"` stores a plain draft with `approval: null`. It stays private until staff publish it in the AdminCP, and nobody is told to review it.
Some people skip the queue. A moderator holding `can_approve` in the container publishes and edits their own posts immediately, and so does a root role. A moderator editing through `can_edit` always applies the edit at once, even to someone else's record. Those permissions are [scoped to containers](/docs/dev/moderation/scoped-permissions#container-scoped-permissions).
AdminCP staff work outside this flow: their edits apply directly, as always.
## What the author sees [#what-the-author-sees]
Every public write response carries `approval`. It is `null` when nothing waits, and otherwise describes the submission:
```json title="PATCH /api/@vitnode/forum/content/topics/42 → 200"
{
"approval": {
"id": 12,
"kind": "edit",
"reason": null,
"status": "pending",
"submittedAt": "2026-10-13T10:02:11.004Z",
"values": { "title": "The editor forgets my draft on Safari", "body": { "type": "doc", "content": [] } }
},
"id": 42,
"slug": "the-editor-forgets-my-draft",
"status": "published",
"publishedAt": "2026-10-13T09:40:02.118Z",
"version": 3,
"values": { "title": "The editor forgets my draft", "body": { "type": "doc", "content": [] } }
}
```
For a proposal, `values` is still the live record and `approval.values` holds what the author asked for, so an edit page can show both.
| null' },
}}
/>
`GET /{id}/edit` returns the record's latest submission when it is pending, or rejected and not replaced yet, so the author's edit page can say "waiting for a moderator" or show the reason. The shape is `zodContentApprovalState` from `@vitnode/core/content`.
To list everything an author sent, call the core moderation module. It returns pending, approved and rejected submissions, newest first, for the signed-in member. Pass `pluginId` to keep only your plugin's submissions. The filter runs before the page is cut, so every page is full and `total` counts only yours:
```ts
import { fetcher } from "@vitnode/core/tanstack/fetcher";
export const fetchMySubmissions = async (page: number) => {
const res = await fetcher({
plugin: "@vitnode/core",
method: "get",
module: "moderation",
path: "/approvals/mine",
args: { query: { page, pluginId: "@vitnode/forum" } },
});
if (!res.ok) throw new Error("Could not load your submissions.");
return await res.json();
};
```
Each item has `kind`, `status`, `title`, `contentTypeId`, `itemId`, the container, `reason` and the dates. A guest gets `401`. The Forum plugin's `pending-page.tsx` renders this list at `/forum/me/pending`.
## Show it on your pages [#show-it-on-your-pages]
Readers never see a pending record, so the author needs to hear what happened. Three places cover it, all from the `approval` object:
1. **After posting.** When `record.approval?.status === "pending"`, send the author to the record's edit page instead of its public page, which answers `404` until approval. See [Create form](/docs/content-engine/public-write-frontend#write-the-page).
2. **On the edit page.** `GET /{id}/edit` returns the pending or rejected submission. Open the form on the proposal and show a notice above it. [Approval notices](/docs/content-engine/approval-notices) builds this on the Forum plugin's edit page.
3. **In a "my submissions" list.** `GET /moderation/approvals/mine`, shown above, lists everything the author sent. The forum renders it at `/forum/me/pending`.
## What a decision does [#what-a-decision-does]
A moderator approves or rejects from the ModCP or through the [approval routes](/docs/dev/moderation/reference#approval-routes).
- **Approving a create** publishes the draft, which emits the content type's `published` event once. A record a moderator hid stays hidden.
- **Approving an edit** applies the proposal as an ordinary update against the version it was made from. That emits one `updated` event and, on an [editorial](/docs/content-engine/editorial) content type, writes one revision.
- **Rejecting** changes nothing on the record. A new topic stays a draft, a published one keeps its live version, and the optional reason is stored for the author.
Each decision locks the submission first, so two moderators clicking at once get one success. It then locks the record and resolves its container again from the row, so a topic moved to another forum since it was submitted is checked against where it lives now. If the decision cannot go through, the route answers with one of these codes:
| Code | Status | What happened |
| ----------- | ------ | ------------------------------------------------------------------------------------------------- |
| `decided` | `409` | The submission is no longer pending. Someone else decided first, or the author replaced it |
| `stale` | `409` | The record changed after the proposal was made, or the proposal no longer validates. Reject it, and the author can resubmit |
| `gone` | `409` | The record was deleted. The submission is marked `cancelled` |
| `forbidden` | `403` | The record now lives in a container where this moderator has no `can_approve` |
| `notFound` | `404` | No such submission, or one outside the moderator's scope |
Deleting a record cancels its pending submission, from the AdminCP or anywhere else. If staff publish a pending draft from the AdminCP first, approving it later only closes the submission. Changing a container's policy never touches submissions that are already waiting.
## Events [#events]
Opening a submission emits `content.approval.submitted`, and a decision emits `content.approval.approved` or `content.approval.rejected`. They carry the submission id, the content type, the record id, the container, the author and, for decisions, the reviewer. The record's own events are not duplicated: a pending create emits `created` but not `published` until it is approved. Payloads are in [Built-in events](/docs/dev/events/built-in-events#content-approval-events).
To tell authors about decisions in their notification inbox, use the [`moderationDecision` preset](/docs/content-engine/notifications#tell-authors-about-moderation-decisions) instead of a listener: it is stored with the decision and sent exactly once. To tell moderators that something waits, use the [`approvalPending` preset](/docs/content-engine/notifications-api#approvalpending-preset): it is stored with the submission and reaches only moderators whose `can_approve` covers the record's container.
## Check the result [#check-the-result]
In the AdminCP, set a forum's policy to **Approve** for new topics, as in [Publishing rules](/docs/content-engine/container-policies). Sign in as a member and start a topic there. You land on the topic's edit page with the waiting notice, and the topic stays out of the forum until a moderator approves it in the [ModCP](/docs/dev/moderation/review-approvals).
# Caching (/docs/content-engine/caching)
Without Redis, the Content Engine does not cache public reads. Every request to a [public API](/docs/content-engine/public-api) route queries Postgres, and the response carries no `Cache-Control` header:
```bash
curl -si "http://localhost:3000/api/newsroom/content/stories?first=1" | head -4
```
```text
HTTP/1.1 200
access-control-allow-credentials: true
content-type: application/json
cross-origin-opener-policy: same-origin
```
So a published story shows up on the next request, with nothing to expire.
With [Redis](/docs/dev/cache/api) (`REDIS_URL`), the server also keeps the public list and detail responses for up to 60 seconds. Each entry is keyed by the parsed query, the resolved locale and a generation number per content type. Every content write bumps that generation, so a write still shows up on the next request and a stale entry is never read. A record whose future `publishedAt` comes due without a write can take up to that minute to appear. The language list and the container tree behind `includeDescendants` are cached the same way. There is nothing to configure.
Only responses that look the same to every reader are cached. A [hidden](/docs/content-engine/content-visibility) record shown to its author, editor or moderator (on its page or in a list), a preview link and the delivery routes always go to Postgres.
Add caching where it pays off:
| Where the content is read | Cache with | Expire it with |
| --------------------------------------- | --------------------------------------- | ----------------------------------------------------- |
| A page of your VitNode app | TanStack Query, warmed in the loader | Its `staleTime`, or `invalidateQueries` after a write |
| The HTML of a public page in your app | [Page cache](/docs/dev/cache/pages) | Automatic: every content write invalidates it |
| A separate front end with its own cache | That front end's tag cache | `content.revalidateOrigins` and the cache tags below |
| Your own Hono route | [`c.get("cache")`](/docs/dev/cache/api) | `c.get("cache").delete(key)` after a write |
## Cache a public list in the app [#cache-a-public-list-in-the-app]
Wrap the fetcher call in `queryOptions` and warm it in the route loader, exactly as in [Cache app data](/docs/dev/cache/app). Use `defineRoute` from `@vitnode/core/tanstack/plugin-routes`, because its loader context has the `queryClient`:
```tsx title="latest-stories.tsx"
import { queryOptions } from '@tanstack/react-query'
import { fetcher } from '@vitnode/core/tanstack/fetcher'
import { defineRoute } from '@vitnode/core/tanstack/plugin-routes'
export const latestStoriesQuery = () =>
queryOptions({
queryKey: ['newsroom', 'stories', 'latest'],
queryFn: async () => {
const response = await fetcher({
plugin: 'newsroom',
method: 'get',
module: 'content/stories',
path: '/',
args: { query: { first: 5 } },
})
if (response.status !== 200) {
throw new Error(`Loading stories answered ${response.status}.`)
}
const { edges } = await response.json()
return edges
},
})
export const route = defineRoute({
load: async ({ context }) => {
await context.queryClient.query({
...latestStoriesQuery(),
staleTime: 60_000,
})
},
})
```
Each server render starts with an empty query client, so a full page load is always fresh. The `staleTime` only decides how long a visitor's open tab reuses the list during client-side navigation. `staleTime: "static"` keeps it until the tab reloads.
Publishing in the AdminCP refreshes the AdminCP's own list, item and search queries. It cannot reach a visitor's browser, so pick a `staleTime` you are happy to wait out. For your own write routes, call `queryClient.invalidateQueries({ queryKey: ["newsroom", "stories"] })` after the write.
Public routes also send an `x-vitnode-cache-tags` header naming the record they read, such as `content:blog.post:item:3`, or the content type for a list. The page cache stores a page with these tags and invalidates it after every write, hard for a hide, delete, unpublish or slug change. [How cached pages stay fresh](/docs/dev/cache/pages-invalidation#content-engine-invalidation) explains the rules.
## Cache tags [#cache-tags]
When a front end caches public reads under tags, it needs to know which tags a write affects. `@vitnode/core/content` exports pure string builders for that. They read nothing and need no server:
| Builder | Example for `newsroom.story` |
| --------------------------------------------------- | ------------------------------------------------------ |
| `contentPublicListTag(typeId, locale?)` | `content:newsroom.story:list` |
| `contentPublicItemTag(typeId, id, locale?)` | `content:newsroom.story:item:3` |
| `contentPublicSlugTag(typeId, slug, locale?)` | `content:newsroom.story:slug:hello-content-engine` |
| `contentDeliveryTag(typeId, id, locale?)` | `content:newsroom.story:delivery:3` |
| `contentDeliveryRedirectTag(typeId, slug, locale?)` | `content:newsroom.story:redirect:hello-content-engine` |
| `contentDeliverySitemapTag(typeId, locale?)` | `content:newsroom.story:sitemap` |
A locale goes after the kind, so a localized type's Polish list is `content:newsroom.bulletin:list:pl`. An id goes in as text, so a [uuid or bigint](/docs/content-engine/id-strategy) record's item tag carries its exact UUID or decimal string.
`contentInvalidationTags` turns a description of one write into the exact tags to expire. Publishing story `3` returns all six tags above:
```ts title="revalidate.ts"
import { contentInvalidationTags } from '@vitnode/core/content'
const tags = contentInvalidationTags({
contentTypeId: 'newsroom.story',
id: 3,
slugs: ['hello-content-engine'],
wasPublic: false,
isPublic: true,
delivery: { sitemap: { contentChanged: true, indexChanged: true } },
})
```
A write to a record that was a draft before and after returns `[]`, because no public reader ever saw it. On a slug change, pass both slugs so the old URL stops resolving and the new one starts.
## Notify a separate front end [#notify-a-separate-front-end]
If another app renders your content and caches it, list its origin in the API config:
```ts title="apps/api/src/vitnode.api.config.ts"
export const vitNodeApiConfig = buildApiConfig({
content: {
revalidateOrigins: ['https://www.example.com'], // [!code ++]
},
})
```
VitNode then sends a `POST` to `{origin}/api/vitnode/content/revalidate` in these cases:
| Change | Notifies origins |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| A [scheduled](/docs/content-engine/editorial-scheduling) publish or unpublish runs | Yes |
| A record is [hidden or unhidden](/docs/content-engine/content-visibility) | Yes, when that changes what the public can see |
| A publish, unpublish, edit or delete from the AdminCP or the API | No |
Hiding a draft notifies nobody, because nothing public changed. For the changes that send nothing, a front end that caches must expire entries on its own timer, or from a listener for the [content events](/docs/content-engine/events).
The request carries:
- `Authorization: Bearer `, the same secret that runs cron jobs.
- `x-vitnode-timestamp`, the send time in milliseconds.
- A JSON body with the `contentInvalidationTags` input plus `mode`, which is always `"immediate"` for a scheduled run, a hide and an unhide.
The secret travels with the request, so outside development each origin must use `https`. Plain `http` is allowed only for `localhost` and `127.0.0.1`. VitNode sends nothing while `CRON_SECRET` is unset or still the default. It tries each origin twice and does not retry a `403`, which it reads as a wrong secret.
### Build the revalidate endpoint [#build-the-revalidate-endpoint]
The endpoint lives in your front end, not in VitNode. Before you expire anything, check the bearer in constant time and refuse a timestamp more than 5 minutes off, so a captured request cannot be replayed later:
```ts title="is-trusted-revalidation.ts"
import { createHash, timingSafeEqual } from 'node:crypto'
const MAX_SKEW_MS = 5 * 60 * 1000
const digest = (value: string) => createHash('sha256').update(value).digest()
export const isTrustedRevalidation = (request: Request): boolean => {
const secret = process.env.CRON_SECRET
if (!secret) return false
const bearer = /^Bearer (.+)$/.exec(
request.headers.get('authorization') ?? '',
)?.[1]
if (!bearer || !timingSafeEqual(digest(bearer), digest(secret))) return false
const sentAt = Number(request.headers.get('x-vitnode-timestamp'))
return Number.isFinite(sentAt) && Math.abs(Date.now() - sentAt) <= MAX_SKEW_MS
}
```
Hashing both values first gives `timingSafeEqual` two buffers of the same length. Answer `403` when the check fails. Otherwise pass the body to `contentInvalidationTags`, expire those tags in your cache and answer with any `2xx`.
# Comments API (/docs/content-engine/comments-api)
`@vitnode/core/tanstack/comments` turns a Content Engine content type with `thread` into a comment section. `useContentComments` holds the thread's state and actions, and the components render them. For a guided setup, follow [Comments](/docs/content-engine/threads), [Comment actions](/docs/content-engine/threads-editing) and [Replies](/docs/content-engine/threads-frontend).
Everything here is browser code. It calls the Content Engine's own routes for the thread, permissions, writes, deletes, hiding and reports, and those routes decide every permission.
## `useContentComments` [#usecontentcomments]
```tsx
import { useContentComments } from '@vitnode/core/tanstack/comments'
const comments = useContentComments({ queryKey, thread, ...actions })
```
### Options [#options]
| Name | Type | Required | Description |
| ------------- | --------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `queryKey` | `QueryKey` | Yes | The thread's cache key prefix, unique per root record, e.g. `[manifest.id, "comments", article.id]`. The thread is cached under `[...queryKey, "thread"]` and the permissions under `[...queryKey, "permissions", ...]`, so invalidating `queryKey` refreshes both |
| `thread` | `({ after, first }) => Promise` | Yes | `GET /thread` with `root`, `first` and `after` |
| `maxDepth` | `number` | No | The type's `thread.maxDepth`. Without it the comments are flat and **Reply** never shows |
| `pageSize` | `number` | No | Top-level comments per page, 1-50. Defaults to `20` |
| `permissions` | `(ids) => Promise` | No | `GET /permissions` with `ids` joined by commas. Without it every comment has no actions |
| `create` | `({ body, parentId }) => Promise` | No | `POST /` with the root record, `body` and `parent: parentId`. Without it there is no composer |
| `edit` | `{ load(id), save(id, { body, expectedVersion }) }` | No | `GET /{id}/edit` and `PATCH /{id}`. `expectedVersion` is a number with `editorial` and `undefined` without it |
| `delete` | `(id) => Promise` | No | `POST /{id}/delete` |
| `visibility` | `{ hide(id, { reason }), unhide(id) }` | No | `POST /{id}/hide` with an optional `reason` (`null` when empty, at most 500 characters) and `POST /{id}/unhide` |
| `report` | `(id) => ContentTarget` | No | `contentTarget(manifest.id, commentContentType, id)` from `@vitnode/core/content` |
| `record` | `ZodType` | No | Validates every loaded comment's public record and gives it a type. The thread route types records loosely, so pass it when your own rendering reads their fields |
| `field` | `string` | No | The rich-text field with the comment's text. Defaults to `"body"` |
| `onChanged` | `(queryClient) => void \| Promise` | No | Refreshes your other queries after a successful write, such as a comment count elsewhere on the page |
| `branches` | `(ids) => Promise` | No | [`GET /thread/branches`](#get-threadbranches) with `root`, plus `ids` joined by commas only when there are any. Writes then re-read only the branch they touched instead of every loaded page. `live` needs it |
| `live` | `{ contentTypeId, rootId }` | No | The comment content type's `id` and the root record's id. Keeps the thread current over the WebSocket while it is mounted; ignored without `branches`. See [Live comments](/docs/content-engine/threads-live) |
### Callback contract [#callback-contract]
- **Write each `fetcher` call inline** and return its response unchanged. The plugin, module, path, arguments and answer then stay typed from your routes; the hook infers the comment id type (`number`, or `string` for a [uuid](/docs/content-engine/id-strategy) type) from `thread`.
- **Don't check the status yourself.** The hook reads `ok` and `status`: a `2xx` is a success, anything else is reported by the section, and a thrown error counts as a failed request.
- **An action you leave out** never shows. One you wire up still shows only where the server's `can*` answer allows it.
### Controller [#controller]
`useContentComments` returns the controller every component reads. The fields you are most likely to use in a custom layout:
| Name | Description |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tree` | The loaded comments as a tree: `ContentCommentTreeNode[]`, replies in `children` |
| `items` | The same entries, flat and depth first |
| `status` | `"pending"` before the first page, `"error"` when it failed, then `"success"` - also after a failed background refresh, which `refreshError` reports |
| `hasMore`, `loadMore()`, `isLoadingMore` | The next page of top-level comments. `loadMore` resolves to `false` when it failed |
| `isRefreshing`, `retry()` | A refetch over data on screen (not **Load more**), and retrying a failed first load |
| `refreshError`, `retryRefresh()` | A background read of the comments on screen failed, and they stayed as they were. `retryRefresh()` asks again for what it missed and resolves when done |
| `hasNewComments`, `showNewComments()` | With `live`: comments appeared after the last loaded one, at the end of the thread. `showNewComments()` reads only those and adds them below; it resolves to `false` when that failed |
| `liveStatus` | `"off"` (no `live`, or no open WebSocket), `"joining"`, `"live"`, or `"denied"` when the server refused or revoked the subscription |
| `trackDraft(id, open)` | Call with `true` while an edit or reply form is open on `id` and `false` when it closes. A live update that removes that comment keeps it on screen with `removed: true` and its record until then. `useContentCommentItem` calls it for you |
| `replyCount`, `truncated` | Every public comment at any depth, and whether a page held more replies than one answer carries |
| `permissionsOf(id)` | `{ canDelete, canEdit, canHide, canReport, canWarn }`, all `false` until known or after a failed batch |
| `canComment`, `canReply(node)` | Whether the composer and **Reply** show: signed in, `create` given, under `maxDepth`, not hidden |
| `features` | Which actions you wired up |
| `busy` | The action running right now, `{ action, id }` or `null`. A second action waits for it |
| `remove(id)`, `hide(id, reason)`, `unhide(id)` | Run an action and refresh after success - only that comment's branch with `branches`. Resolve to `{ ok: true }` or `{ ok: false, status }`; `status` is `409` when another action was still running and `0` for a network failure |
| `refresh()` | Re-reads every loaded page, its permissions and `onChanged`'s queries |
| `userId` | The signed-in visitor's id, or `null` |
### Thread entries [#thread-entries]
Each entry of `tree` and `items` is a `ContentCommentNode`:
| Field | Description |
| ------------------------ | ---------------------------------------------------------------------------- |
| `id`, `parentId` | The comment and the comment it answers, `null` at the top level |
| `depth` | `1` for a comment on the root record, `2` for a reply to it |
| `record` | The public record, or `null` for a placeholder |
| `deleted` | For a placeholder: `{ byAuthor, createdAt }`, with no text and no author |
| `hidden`, `hiddenReason` | Set only for a hidden comment this reader may see: its author or a moderator |
`buildContentCommentTree(items)` and `countContentCommentReplies(node)` are exported for layouts that work on the flat list.
## `contentCommentsQueryOptions` [#contentcommentsqueryoptions]
The thread's infinite query, for warming the first page in a route's `loader`. It takes the same `queryKey`, `thread`, `pageSize` and `record` as the hook and reads the same cache entry:
```tsx
await context.queryClient
.infiniteQuery(contentCommentsQueryOptions({ queryKey, thread }))
.catch(() => null)
```
Its `queryFn` throws when the thread route answers anything but `2xx`.
## `ContentComments` [#contentcomments]
The complete section: the count, the thread, **Load more comments**, the composer or a sign-in link, the actions menu, the delete confirmation and the report dialog. It scrolls to and rings the comment a `#comment-...` link points to, loading more pages until it appears.
```tsx
```
| Prop | Description |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| `comments` | The controller from `useContentComments` |
| `className` | Classes for the `` |
| `title` | Replaces the "N comments" heading |
| `anchorKey(record)` | What follows `comment-` in each comment's element id. Defaults to the id; return the slug to match slug permalinks |
| `permalink(anchorId)` | The link on each comment's date. Defaults to `#comment-...` on the same page |
| `render.author(record)` | Replaces the author's name |
| `render.body(record)` | Replaces the text |
| `render.meta(record)` | Adds details after the date, such as a badge |
| `render.actions(record)` | Adds buttons next to **Reply** |
The section's element id is `comments`, so `#comments` links scroll to it. Its messages live in the `core.comments` namespace; add it to the page's route `messages` to load them with the page.
## Your own layout [#your-own-layout]
`ContentCommentsRoot` provides the controller to the building blocks below and renders the dialogs they open. It adds the comment messages to the page's, so your own components inside keep their translations.
```tsx
import {
ContentCommentActions,
ContentCommentComposer,
ContentCommentsComposer,
ContentCommentsLoadMore,
ContentCommentsRoot,
useContentCommentItem,
} from '@vitnode/core/tanstack/comments'
const MyComment = ({ node }) => {
const item = useContentCommentItem(node)
if (item.editing) {
return (
)
}
return (
{/* your own rendering of node.record */}
)
}
;
{comments.tree.map((node) => (
))}
```
| Export | What it is |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ContentCommentsRoot` | Provides `comments` to the components below; takes a `fallback` shown while the messages load |
| `useContentCommentItem(node)` | One comment's state: `permissions` (the server's answers limited to wired actions), `canReply`, `editing`, `startEditing()`, `stopEditing()`, `isReplying`, `setIsReplying`, `isBusy`, and `isRemoved` when a live update removed the comment under an open form |
| `ContentCommentActions` | The **More actions** menu with the hide-reason prompt. `children` adds your own menu items |
| `ContentCommentComposer` | The comment form, lazy-loaded: `mode="create"` with `parentId`, or `mode="edit"` with `id` and `editable`. `unavailable` (a translated reason) keeps the text but hides the submit button |
| `ContentCommentsLiveStatus` | **Show new comments** and the refresh-failed notice, with a polite screen reader announcement. Renders nothing while there is nothing to say |
| `ContentCommentItem` | One comment as the default section draws it |
| `ContentCommentPlaceholder` | The anonymous stand-in for a removed comment |
| `ContentCommentsComposer`, `ContentCommentsLoadMore` | The new-comment card and the load-more button |
| `contentCommentAuthor(record)`, `contentCommentAuthorName(person)` | Read the `author` person and the name to show |
| `useContentCommentErrorToast()` | Shows the section's message for a failed action's status |
The Blog plugin's `plugins/blog/src/pages/post-comments.tsx` is a complete custom layout: rail connectors, collapsible branches, share buttons and slug permalinks, with every action from these components.
## Outcomes and errors [#outcomes-and-errors]
- **Writes.** The composer posts through [`useContentPublicWrite`](/docs/content-engine/public-write-form-api): a refused write keeps the text and shows the reason, and with `editorial` a stale edit shows the version-conflict alert. A success reads the answer's `status` and `approval`: **Comment posted** only when it is public, **saved as a draft** or **waiting for a moderator** otherwise.
- **Actions.** Delete, hide and unhide show **Comment deleted**, **Comment hidden** or **Comment visible again** after the server accepts them. When it refuses, the section shows one message for the cause: signed out, not allowed, gone, busy or unknown.
- **Loading.** A failed first load shows **Try again**; a failed **Load more** keeps the loaded comments and says it failed. A failed background refresh keeps them too; `ContentCommentsLiveStatus` offers **Try again**.
## `GET /thread/branches` [#get-threadbranches]
Every content type with `thread` also gets `GET /{publicApi.path}/thread/branches`. It re-reads a few top-level comments already on screen, each with every reply below it, using the same root check, visibility, placeholders, depth and truncation as `/thread`. `useContentComments` calls it through `branches`.
```txt
GET /api/newsroom/content/article-comments/thread/branches?root=1&ids=4,9
```
| Query | Required | Description |
| ------ | -------- | -------------------------------------------------------------------------------------------- |
| `root` | Yes | The root record's id |
| `ids` | No | Up to 10 top-level comment ids, joined by commas. Duplicates are ignored. Without it, only the counts are read |
| Response field | Description |
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `branches` | One entry per requested id, in the order asked: `{ id, status: "ok", items }` or `{ id, status: "gone" }` |
| `items` | The top-level comment first, then every reply below it, as [thread entries](#thread-entries) |
| `pageInfo.totalCount`, `replyCount`, `truncated` | The thread's current counts, as on `/thread` |
`gone` means this reader no longer sees the branch: deleted, hidden or unpublished with no visible reply left, not a top-level comment, or under another root. An unreadable root answers `404`, as on `/thread`; more than 10 or malformed ids answer `400`.
Guests and readers who can't see hidden comments get the same answer, served from the [public read cache](/docs/content-engine/caching) with `Cache-Control: no-cache`. Readers who may see hidden comments, and readers of a hidden root, get a `private, no-store` answer.
## Related [#related]
- [Comments](/docs/content-engine/threads): the guided setup.
- [Permissions API](/docs/content-engine/public-permissions-api): `useContentPermissions`, which the hook uses for `permissionsOf`.
- [thread reference](/docs/content-engine/reference#thread): the `thread` option on the content type.
# Container pages (/docs/content-engine/container-frontend)
This guide builds the member-facing side of the newsroom plugin's desks: a `/desks` page with the nested desk tree, a `/desks/:slug` page that lists the letters to the editor sent to a desk and every desk below it, and a desk picker on the "Write a letter" form.
The finished pages are in `plugins/newsroom/src/pages/`, in the `desk-*` and `letter-*` files. The code below is the same, with some styling trimmed.
## Before you begin [#before-you-begin]
You need a container collection with `publicApi`, and a content type whose `field.container()` is public, filterable and writable on create, as set up in [Containers](/docs/content-engine/containers#add-a-container-collection). The newsroom's collection has `publicApi.path: "desks"`, so the fetcher's module is `content/desks`.
The collection's public routes are read-only and need no session:
| Route | Returns |
| ----------------- | ---------------------------------------------------------------------------------------------- |
| `GET /` | `{ items }`: every container in tree order. `?parent=root` or `?parent={id}` returns one level |
| `GET /{idOrSlug}` | `{ container, ancestors, children }`: ancestors root first, direct children in order |
Each item is `{ id, parentId, name, slug, position, depth, metadata }`, where `metadata` holds only `publicApi.fields`. An unknown container or `parent` answers `404`. A numeric segment is read as an id, anything else as a slug.
### Add the routes [#add-the-routes]
Register the two desk pages in `src/routes.ts`, and give the create page a `search` parser so it can read `?desk=`. A `pendingComponent` is the fallback while a page suspends, not a navigation screen. Navigations keep the current page and show the top progress bar. It can render before the page's chunk arrives, so import it directly rather than through `lazy()`:
```ts title="plugins/newsroom/src/routes.ts"
// [!code ++:4]
import {
FeedPendingSkeleton,
RoutePendingSkeleton,
} from "@vitnode/core/tanstack/pending";
import { deskSearch } from "./pages/desk-search"; // [!code ++]
import { letterNewSearch } from "./pages/letter-search"; // [!code ++]
export const routes = definePluginRoutes([
// [!code ++:13]
page("/desks", {
component: lazy(() => import("./pages/desks-page")),
messages: ["newsroom.desks"],
pendingComponent: RoutePendingSkeleton,
}),
page("/desks/:slug", {
component: lazy(() => import("./pages/desk-page")),
messages: ["newsroom.desks"],
pendingComponent: FeedPendingSkeleton,
search: deskSearch,
}),
page("/letters/new", {
component: lazy(() => import("./pages/letter-new-page")),
messages: ["newsroom.letters"],
requires: "authenticated",
search: letterNewSearch, // [!code ++]
}),
]);
```
`deskSearch` keeps a valid `cursor` for paging through letters, and `letterNewSearch` keeps a positive `desk` id. Both are small functions in `desk-search.ts` and `letter-search.ts`. The strings live under `newsroom.desks` in `src/locales/en.json`.
### Load the tree [#load-the-tree]
Create a helper that reads every desk. The list comes back in tree order, flat, so one request loads the whole tree:
```ts title="plugins/newsroom/src/pages/desks-data.ts"
import { fetcher } from "@vitnode/core/tanstack/fetcher";
import { manifest } from "@/manifest.gen";
export const fetchDesks = async () => {
const res = await fetcher({
plugin: manifest.id,
method: "get",
module: "content/desks",
path: "/",
args: { query: {} },
});
if (res.status !== 200) throw new Error("Loading the desks failed.");
const { items } = await res.json();
return items;
};
export type Desk = Awaited>[number];
const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
export const deskColor = (desk: Pick): null | string =>
typeof desk.metadata.color === "string" && HEX_COLOR.test(desk.metadata.color)
? desk.metadata.color
: null;
```
`Desk` is inferred from the API, so `desk.metadata.color` is typed as `string | null` from the definition's fields, and `desk.metadata.locked` is a compile error because `locked` is not public. `deskColor` accepts only a hex value before it goes into a `style` attribute, because an admin typed it.
The pages read the list through one TanStack Query entry, so the desks page, the letter form and a desk page share it:
```ts title="plugins/newsroom/src/pages/desk-queries.ts (excerpt)"
export const desksQueryOptions = () => ({
meta: LOADER_DATA_QUERY_META,
queryFn: fetchDesks,
queryKey: deskQueryKeys.desks(),
staleTime: RECORD_STALE_TIME,
});
```
### Render the tree [#render-the-tree]
`contentContainerTree` from `@vitnode/core/content` nests a tree-ordered list: each node gets a `children` array. Render it recursively as nested lists inside a labelled `nav`, so screen readers announce the structure:
```tsx title="plugins/newsroom/src/pages/desk-tree.tsx"
import type { ContentContainerTreeNode } from "@vitnode/core/content";
import { HrefLink } from "@vitnode/core/tanstack/link";
import type { Desk } from "./desks-data";
import { deskHref } from "./desk-search";
import { deskColor } from "./desks-data";
export const DeskColorDot = ({ desk }: { desk: Desk }) => {
const color = deskColor(desk);
return (
);
};
const DeskTreeItems = ({
nodes,
}: {
nodes: ContentContainerTreeNode[];
}) => (
);
export const DeskTree = ({
label,
nodes,
}: {
label: string;
nodes: ContentContainerTreeNode[];
}) => (
);
```
`contentContainerTree` keeps the server's order, so siblings appear in the order staff arranged them. It works on any rows with `id` and `parentId`, including the AdminCP records.
### Add the desks page [#add-the-desks-page]
The route's `load` reads the cached desks and nests them, and the page shows the tree, or an empty state when no desk exists yet. The same `load` also warms the latest letters list that the page shows under the tree:
```tsx title="plugins/newsroom/src/pages/desks-page.tsx (excerpt)"
import { contentContainerTree } from "@vitnode/core/content";
import {
defineRoute,
type RouteLoadContext,
} from "@vitnode/core/tanstack/plugin-routes";
import { useTranslations } from "use-intl";
import { desksQueryOptions } from "./desk-queries";
import { DeskTree } from "./desk-tree";
import { LatestLetters } from "./latest-letters";
import { lettersQueryOptions } from "./letter-list";
const loadDesks = async (
queryClient: RouteLoadContext["queryClient"],
locale: string,
) => {
const [desks] = await Promise.all([
queryClient.query(desksQueryOptions()),
// No `LOADER_DATA_QUERY_META`: the entry is dehydrated, so
// `LatestLetters` finds it in the browser and renders on the server.
queryClient
.query(lettersQueryOptions({ locale, search: {} }))
.catch(() => null),
]);
return { tree: contentContainerTree(desks) };
};
type DesksPageData = Awaited>;
export const route = defineRoute({
load: async ({ context }) =>
await loadDesks(context.queryClient, context.locale),
head: ({ t }) => ({
description: t("newsroom.desks.desc"),
title: t("newsroom.desks.title"),
}),
breadcrumb: DesksBreadcrumb,
});
const DesksPage = ({ loaderData }: PluginRoutePageProps) => {
const t = useTranslations("newsroom.desks");
return (
{/* The header: title, description and a "Write a letter" button */}
{loaderData.tree.length === 0 ? (
{/* "No desks yet" */}
) : (
)}
);
};
export default DesksPage;
```
The full page also has the breadcrumb component, a **Write a letter** button and an `Empty` state with an icon.
### Add the desk page [#add-the-desk-page]
`/desks/:slug` makes two requests. The detail route returns the desk, its ancestors for the breadcrumb and its child desks. The letters list is filtered by the desk, and `includeDescendants: "true"` widens the filter to every desk below it, so **Politics** also lists what was sent to **Elections**:
```tsx title="plugins/newsroom/src/pages/desk-page.tsx (excerpt)"
import { contentPageItem } from "@vitnode/core/tanstack/content";
import { fetcher } from "@vitnode/core/tanstack/fetcher";
import { z } from "zod";
import { manifest } from "@/manifest.gen";
import type { DeskSearch } from "./desk-search";
import { cachedDeskId, queryDesk } from "./desk-queries";
const PAGE_SIZE = 20;
const zodLetterRow = z.object({
id: z.number(),
publishedAt: z.string().nullable(),
slug: z.string().nullable(),
title: z.string(),
});
const fetchLetters = async (deskId: number, cursor?: string) => {
const filters = {
desk: String(deskId),
includeDescendants: "true",
};
const list = await fetcher({
plugin: manifest.id,
method: "get",
module: "content/letters",
path: "/",
args: {
query: {
...filters,
first: String(PAGE_SIZE),
...(cursor ? { cursor } : {}),
},
},
});
if (list.status !== 200) throw new Error("Loading the letters failed.");
const { edges, pageInfo } = await list.json();
return {
letters: z.array(zodLetterRow).parse(edges),
nextCursor: pageInfo.hasNextPage ? pageInfo.endCursor : null,
};
};
const loadDesk = async (
queryClient: RouteLoadContext["queryClient"],
idOrSlug: string,
{ cursor }: DeskSearch,
) => {
// The list needs the desk's id. When the desks index already cached it,
// both requests go out together instead of one after the other.
const knownId = cachedDeskId(queryClient, idOrSlug);
const [desk, early] = await Promise.all([
queryDesk(queryClient, idOrSlug),
// A stale id (the desk was moved or deleted since) is not this page's
// error: the desk read below decides, and the list is fetched again.
knownId === null ? null : fetchLetters(knownId, cursor).catch(() => null),
]);
const { ancestors, children, container } = contentPageItem(desk);
const page =
early && knownId === container.id
? early
: await fetchLetters(container.id, cursor);
return {
ancestors,
children,
container,
...page,
isFirstPage: cursor === undefined,
};
};
```
- `queryDesk` in `desk-queries.ts` calls `GET content/desks/{idOrSlug}` and returns `null` for a `404`. `contentPageItem(null)` turns that into the route's not-found page.
- The filter parameter is named after the field, `desk`, and works only because `desk` is in `publicApi.filterableFields`. Without `includeDescendants`, it matches that one desk.
- Filter parameters are not part of the inferred query type yet, so they are spread in from a small object instead of written as literal keys.
- An unknown desk id in the filter answers `404`, not an empty list, so a stale link never looks like an empty desk.
- `nextCursor` goes into `?cursor=` for an **Older letters** link. Pass it back unchanged.
Declare the trail as a breadcrumb group, one crumb per ancestor, and give the route a `notFound` component for the 404:
```tsx title="plugins/newsroom/src/pages/desk-page.tsx (excerpt)"
export const route = defineRoute({
load: async ({ context, params, search }) =>
await loadDesk(context.queryClient, params.slug, search),
head: ({ loaderData }) => ({
description: loaderData?.container.metadata.description ?? undefined,
title: loaderData?.container.name,
}),
breadcrumb: {
group: ({ loaderData }) => (
<>
}>
{loaderData.ancestors.map(ancestor => (
}
>
{ancestor.name}
))}
{loaderData.container.name}
>
),
},
notFound: DeskNotFound,
});
```
The page renders the children with the same `DeskTree`, the letters as a list of links, and a **Write a letter** link to `/letters/new?desk={container.id}`. See the full component in `desk-page.tsx`.
### Let members pick a desk [#let-members-pick-a-desk]
Load the same cached desks for the create page and turn them into select options, indented by depth so the select reads like the tree:
```tsx title="plugins/newsroom/src/pages/letter-new-page.tsx (excerpt)"
const loadDeskOptions = async (queryClient: RouteLoadContext["queryClient"]) =>
(await queryClient.query(desksQueryOptions())).map(desk => ({
label: `${"— ".repeat(desk.depth - 1)}${desk.name}`,
value: String(desk.id),
}));
export const route = defineRoute({
load: async ({ context }) => await loadDeskOptions(context.queryClient),
});
```
Add the desk to the form schema. A select works with strings, so the ids become a `z.enum`, preselected from `?desk=` when it names a real desk:
```tsx title="plugins/newsroom/src/pages/letter-form.tsx (excerpt)"
const createLetterCreateFormSchema = (
t: (
key: "body.required" | "desk.required" | "title.max" | "title.min",
) => string,
ids: [string, ...string[]],
selected: string | undefined,
) => {
const desk = z.enum(ids, { error: t("desk.required") });
return createLetterFormSchema(t, {
body: emptyRichTextDocument(),
title: "",
}).extend({
desk:
selected !== undefined && ids.includes(selected)
? desk.default(selected)
: desk,
});
};
```
Render it with `AutoFormSelect` before the title and body fields:
```tsx title="plugins/newsroom/src/pages/letter-form.tsx (excerpt)"
{
id: "desk",
component: props => (
),
},
```
On submit, send the desk as a number inside `values`, like every other writable field. `LETTER_FIELDS` in `letter-form.tsx` is `["title", "body", "desk"]`:
```tsx title="plugins/newsroom/src/pages/letter-new-page.tsx (excerpt)"
const write = useContentPublicWrite({
fields: LETTER_FIELDS,
uniqueField: "title",
});
const onSubmit: AutoFormOnSubmit = async (
{ desk, ...values },
form,
) => {
const record = await write.submit(
form,
async () =>
await fetcher({
plugin: manifest.id,
method: "post",
module: "content/letters",
path: "/",
args: { body: { values: { ...values, desk: Number(desk) } } },
}),
);
if (!record) return;
setIsLeaving(true);
await invalidateLetterLists(queryClient);
await navigate(
record.slug === null
? letterEditHref(record.id)
: letterHref(record.slug, { created: true }),
);
};
```
The server never trusts the id. It reads the desk back inside the write's transaction and checks that it belongs to `newsroom.desks`. A desk that was deleted while the form was open, or one from another collection, answers `400` with an issue on the `desk` field:
```json
{
"code": "CONTENT_INVALID_INPUT",
"contentTypeId": "newsroom.letter",
"issues": [
{
"code": "unavailable",
"field": "desk",
"message": "The selected container does not exist."
}
]
}
```
Because `"desk"` is in `fields`, [`useContentPublicWrite`](/docs/content-engine/public-write-frontend) shows that issue under the desk select.
The edit form stays as it was. A container field cannot be in `publicWrite.update.fields`, so moving a letter to another desk is a staff edit in the AdminCP.
## Check the result [#check-the-result]
1. Create **Politics** with **Elections** inside it in the AdminCP, then open `/desks`. Both desks show, **Elections** nested under **Politics**.
2. Open **Elections** and click **Write a letter**. The form opens with **— Elections** preselected. Send it.
3. Open `/desks/politics`. The letter is listed there too, because of `includeDescendants`, and the breadcrumb ends with **Desks** and **Politics**.
4. Open `/desks/nope`. The not-found page shows.
## Errors to handle [#errors-to-handle]
| Request | Answer | What the page does |
| --------------------------------------------------------------- | ---------------------- | ------------------------------------------------------ |
| `GET content/desks/{idOrSlug}` for an unknown desk | `404` | `contentPageItem(null)` renders the route's `notFound` |
| `GET content/desks?parent={id}` for an unknown parent | `404` | Treat it like a missing desk |
| `GET content/letters?desk={id}` for an unknown desk | `404` | Treat it like a missing desk |
| `POST content/letters` with a missing, deleted or foreign desk | `400`, issue on `desk` | Show the message under the select |
| `POST content/letters` with no `desk` at all | `400`, issue on `desk` | The form's own `required` check catches it first |
The [public write status codes](/docs/content-engine/public-write-api#status-codes) cover sign-in, permission and rate-limit answers, which work the same with or without containers.
# Container tree (/docs/content-engine/container-hierarchy)
A container collection is a tree. This page explains the rules every change to that tree follows, whether it comes from the AdminCP or from your own code, and shows how to use the container service on the server. It uses the newsroom plugin's `newsroom.desks` collection from [Containers](/docs/content-engine/containers).
## Depth [#depth]
`depth` is 1 for a root, 2 for its children, and so on. `hierarchy.maxDepth` caps it and counts roots, so the newsroom's `maxDepth: 3` allows **Politics → Elections → Local** and nothing below **Local**.
- The default is 5, the ceiling is 10.
- `hierarchy: { enabled: false }` keeps every container at the root: a flat, ordered list. Any `parentId` is refused.
- A move checks the whole subtree it carries. Moving a desk that has children under a deep parent is refused if the deepest child would cross the limit.
## Ordering [#ordering]
Siblings are ordered by `ordering.mode`:
| Mode | Order | Reordering |
| -------------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| `manual` | `position`, the order staff drag them into | Allowed. `position` is zero-based among siblings and kept as `0..n-1` |
| `alphabetical` | `name`, case-insensitive | Ignored. A new or moved container goes last by position, but reads sort by name. Moving to another parent still works |
Both modes break ties by `id`, so two reads of the same tree always agree.
## Moves and reorders [#moves-and-reorders]
One operation covers both: `move(id, { parentId, position })`. `parentId: null` moves to the root. `position` is the index among the new siblings **after** the container has left its old place. So moving the first of three siblings to `position: 2` puts it last.
A move is refused, and changes nothing, when:
| Code | Status | When |
| ----------------- | ------ | --------------------------------------------------------------------------------------- |
| `cycle` | 400 | The new parent is the container itself or one of its descendants |
| `parentNotFound` | 400 | The new parent does not exist in this collection |
| `maxDepth` | 400 | The container or its deepest descendant would be too deep, or the hierarchy is disabled |
| `invalidPosition` | 400 | `position` is negative or past the end of the sibling list |
| `notFound` | 404 | The container does not exist |
The old and the new sibling lists are both renumbered, so positions never have gaps.
## Safe deletion [#safe-deletion]
Deleting never cascades. A container is deleted only when it is empty:
- `hasChildren` (409): it still has child containers. Move or delete them first.
- `hasContent` (409): a record of any content type that uses this collection still points at it. Move or delete those records first.
The database enforces the same rules. Both `parentId` and every `field.container()` column are foreign keys with `ON DELETE RESTRICT`, so a delete can never orphan a desk or a letter, even if another request slips in between the check and the delete. The remaining siblings are renumbered to close the gap.
## Slugs [#slugs]
A slug addresses one container of one collection, so `politics` can exist once in `newsroom.desks` and once in another collection. A slug you pass is normalized (lowercase ASCII, dashes) and must be free, or the write fails with `slugTaken`. A missing slug is derived from the name, with `-2`, `-3` and so on added until it is free. A slug that normalizes to nothing, such as `"!!!"`, fails with `slugEmpty`.
## Concurrent edits [#concurrent-edits]
Two admins dragging desks at the same moment cannot corrupt the tree. Every write to a collection:
1. Takes a transaction-scoped Postgres advisory lock for that collection, so writes to one collection run one after another. Different collections never wait for each other.
2. Reads the whole tree inside the transaction, so it plans against what the previous write committed.
3. Checks every rule before changing a single row. A refused write leaves the tree exactly as it was.
A collection holds at most 5,000 containers (`limitReached`, 409). The whole tree is read in one query, so a read costs the same at any depth and never runs one query per level.
## Use the service on the server [#use-the-service-on-the-server]
`createContentContainerService` is the one way to read and change a collection. The AdminCP routes and the public routes both use it, so your code gets the same rules, cache expiry and events. Call it inside any Hono handler with the request context. Here is a route you could add to the newsroom plugin. It files a desk under an **Archive** desk and locks it:
```ts title="src/api/modules/desks/routes/archive.route.ts"
import { createContentContainerService } from "@vitnode/core/content/server";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";
import { buildRoute } from "@/api/builders";
import { deskContainers } from "@/content/desks";
import { manifest } from "@/manifest.gen";
export const archiveDeskRoute = buildRoute({
adminStaffPermission: { module: "newsroom_desks", permission: "can_edit" },
route: {
method: "post",
path: "/{id}/archive",
description: "Move a desk under the Archive desk and lock it",
request: { params: z.object({ id: z.coerce.number().int().positive() }) },
responses: {
200: { description: "Desk archived" },
404: { description: "Desk or Archive not found" },
},
},
handler: async c => {
const { id } = c.req.valid("param");
const desks = createContentContainerService(c, {
definition: deskContainers,
pluginId: manifest.id,
});
const archive = await desks.findBySlug("archive");
if (!archive) {
throw new HTTPException(404, {
message: "Create an Archive desk first.",
});
}
const siblings = await desks.children(archive.id);
await desks.move(id, { parentId: archive.id, position: siblings.length });
await desks.update(id, { metadata: { locked: true } });
return c.json({ message: "Desk archived." }, 200);
},
});
```
Refused writes throw a `ContentContainerError` with `code`, `status` (400, 404 or 409) and a readable `detail`. The generated AdminCP routes turn it into a response body of `{ code, message }`, typed by `zodContentContainerError`. In your own route, catch it or let it surface as a 500.
| Method | Returns | Behavior |
| -------------------- | --------------------------- | ---------------------------------------------------------------------------------------------- |
| `list()` | `Promise` | Every container, in tree order: each parent, then its subtree |
| `children(parentId)` | `Promise` | Direct children in sibling order. `null` returns the roots |
| `ancestors(id)` | `Promise` | Every container above `id`, root first. Empty for a root or an unknown id |
| `descendantIds(id)` | `Promise` | `id` plus every id below it, or `null` when `id` does not exist |
| `findById(id)` | `Promise` | One container |
| `findBySlug(slug)` | `Promise` | One container by its exact slug |
| `create(input)` | `Promise` | `{ name, slug?, parentId?, position?, metadata? }`. Goes last when `position` is left out |
| `update(id, input)` | `Promise` | `{ name?, slug?, metadata? }`. `metadata` is a partial patch, validated against the definition |
| `move(id, input)` | `Promise` | `{ parentId, position }`, as described in [Moves and reorders](#moves-and-reorders) |
| `delete(id)` | `Promise` | Deletes an empty container, as described in [Safe deletion](#safe-deletion) |
| `toPublic(record)` | `PublicRecord` | Drops every metadata field not in `publicApi.fields` |
A record is `{ id, parentId, name, slug, position, depth, metadata, createdAt, updatedAt }`, with `metadata` typed from the definition's fields. `ContentContainerRecord` and `ContentContainerPublicRecord` from `@vitnode/core/content` name those types.
The tree helpers the service uses are pure and browser-safe, exported from `@vitnode/core/content`: `contentContainerTree` nests a list, `orderContentContainers` sorts rows into tree order with their depth, and `contentContainerAncestors` and `contentContainerSubtreeIds` walk it.
## Events [#events]
Each successful write emits one event after its transaction commits. A write that is refused emits nothing, and an update that changes nothing emits nothing.
| Event | Payload |
| --------------------------- | --------------------------------------------------------------------------- |
| `content.container.created` | `{ definitionId, pluginId, containerId, parentId }` |
| `content.container.updated` | `{ definitionId, pluginId, containerId, parentId, changedFields }` |
| `content.container.moved` | `{ definitionId, pluginId, containerId, parentId, fromParentId, position }` |
| `content.container.deleted` | `{ definitionId, pluginId, containerId, parentId }` |
Every collection shares the same names, so filter on `definitionId`. This listener logs desk moves:
```ts title="src/api/lib/desk-listeners.ts"
import { buildEventListener } from "@vitnode/core/api/lib/events";
export const deskMovedListener = buildEventListener({
event: "content.container.moved",
name: "log-desk-moves",
handler: async (c, payload) => {
if (payload.definitionId !== "newsroom.desks") return;
await c
.get("log")
.debug(
`Desk ${payload.containerId} moved from ${payload.fromParentId ?? "the root"} to ${payload.parentId ?? "the root"}`,
);
},
});
```
`changedFields` names `name`, `slug` and the metadata fields whose value actually changed, or `policies` when the container's [publishing policies](/docs/content-engine/container-policies) were saved. A reorder among siblings is a `moved` event with the same `fromParentId` and `parentId`. Register listeners as described in [Events](/docs/dev/events). [Built-in events](/docs/dev/events/built-in-events#content-container-events) has the field-by-field payloads.
Every write also expires the [page cache](/docs/content-engine/caching) entries that read the collection, including pages that list content filtered by one of its containers, so a renamed desk shows its new name without a manual purge.
Next, build pages on top of the tree in [Container pages](/docs/content-engine/container-frontend).
# Publishing rules API (/docs/content-engine/container-policies-api)
Exact names, values and behavior of container publishing policies. For a guided setup, follow [Publishing rules](/docs/content-engine/container-policies). Examples use the Forum plugin's `forum.forums` collection.
## `policies` option [#policies-option]
`defineContentContainer({ policies })` from `@vitnode/core/content`:
```ts title="plugins/forum/src/content/forums.ts"
policies: {
defaults: { publish: "immediate", edits: "immediate", authorEdit: "always" },
contentTypes: {
"forum.comment": { authorEdit: "window", authorEditMinutes: 30 },
},
},
```
| Name | Type | Required | Default | Description |
| -------------- | -------------------------------------- | -------- | ------- | ------------------------------------------------------------------- |
| `defaults` | policy | No | `{}` | Applies to every content type filed in the collection |
| `contentTypes` | `Record` | No | `{}` | Per content type, such as `"forum.comment"`. Wins over `defaults` |
Omit `policies`, or set it to `false`, and the collection does not take part: its content types use `publicWrite.create.status`, owners edit for as long as `update.own` allows, `can_edit` stays unscoped and no `can_approve` exists. `policies: {}` turns the feature on with every key on its fallback.
## Policy keys [#policy-keys]
A policy is a partial object of these keys. Each one is resolved on its own.
| Key | Values | Fallback | Description |
| ------------------- | --------------------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `create` | `"members"` \| `"moderators"` | `"members"` | Who may create. `"moderators"` means `can_edit` holders in the container |
| `publish` | `"immediate"` \| `"approve"` | From `publicWrite.create.status`: `"published"` → `"immediate"`, `"draft"` → `"approve"` | Whether a new record goes live or waits as a draft with a submission |
| `edits` | `"immediate"` \| `"approve"` | `"immediate"` | Whether an author's edit of a published record applies or becomes a proposal |
| `authorEdit` | `"always"` \| `"never"` \| `"window"` | `"always"` | How long the owner may edit |
| `authorEditMinutes` | Whole number from 1 to 525600 (a year) | `60` | The window for `"window"`, counted from the record's server `createdAt` |
The constants are exported from `@vitnode/core/content`: `CONTENT_CONTAINER_POLICY_KEYS`, `CONTENT_CONTAINER_POLICY_CREATE`, `CONTENT_CONTAINER_POLICY_MODES`, `CONTENT_CONTAINER_POLICY_AUTHOR_EDIT` and `CONTENT_CONTAINER_POLICY_MAX_MINUTES`.
## Resolution order [#resolution-order]
For each key, the first layer that sets it wins:
1. the record's container's override for the content type;
2. the nearest ancestor's override, walking `parentId`;
3. `policies.contentTypes[contentTypeId]`;
4. `policies.defaults`;
5. the fallback in the table above.
A missing key inherits. An explicit value, including `"never"` or a value equal to the parent's, is an override and stops the walk. The engine never stores `undefined`, and empty per-type objects are dropped on save.
The record's container is always resolved on the server: from its `field.container()`, or for a `field.relation({ container: true })`, from the related record's container. A comment follows its topic, whatever the payload claims.
## Who passes which rule [#who-passes-which-rule]
| Check | Passes |
| ------------------------- | ----------------------------------------------------------------------------------------- |
| Create with `"moderators"` | `can_edit` for the container, a root role |
| Skip `publish` / `edits` approval | `can_approve` for the container, a root role |
| Edit any record | `can_edit` for the container, a root role. Independent of `authorEdit` |
| Edit own record | The owner, while `update.own` is on, the record is not hidden, one of their roles has **Allow editing own content** with its **Time to edit** still open, and `authorEdit` allows it |
| Delete any record | `can_delete` for the container, a root role |
| Delete own record | The owner, when one of their roles has **Allow deleting own content** |
| Hide or unhide any record | `can_hide`, a root role |
| Hide own record | The owner, when one of their roles has **Allow hiding own content**; they may unhide only what they hid themselves |
Container scopes are explained in [Container-scoped permissions](/docs/dev/moderation/scoped-permissions#container-scoped-permissions).
## Refusals on the public write routes [#refusals-on-the-public-write-routes]
Both answer `403` with `"code": "CONTENT_FORBIDDEN"` and one issue whose `field` is `null`:
| Issue code | Constant | When |
| -------------------- | ------------------------------------------------- | -------------------------------------------------------------------------- |
| `edit_window_closed` | `CONTENT_PUBLIC_WRITE_ISSUE_CODES.editWindowClosed` | The owner edits a public record after `authorEdit` stopped allowing it |
| `moderators_only` | `CONTENT_PUBLIC_WRITE_ISSUE_CODES.moderatorsOnly` | A create in a container with `create: "moderators"` by a non-moderator |
```json title="PATCH /api/@vitnode/forum/content/comments/18 → 403"
{
"code": "CONTENT_FORBIDDEN",
"contentTypeId": "forum.comment",
"issues": [
{ "code": "edit_window_closed", "field": null, "message": "Public write denied: forbidden." }
]
}
```
An owner editing a record the public cannot read, such as a hidden one, still gets `404` with no issue, so the answer never confirms it exists. A submission opened by `publish` or `edits` is described in [Approvals](/docs/content-engine/approvals).
## AdminCP routes [#admincp-routes]
Mounted only for a collection with policies, in the admin module, under `/api/{pluginId}/admin/content/{admin.permissionModule}`. For the forum that is `/api/@vitnode/forum/admin/content/forum_forums`.
| Method and path | Admin permission | Body | Success |
| --------------------- | ---------------- | --------------- | -------------------------- |
| `GET /{id}/policies` | `can_view` | | `200` with the report |
| `PUT /{id}/policies` | `can_edit` | `{ overrides }` | `200` with the new report |
`PUT` replaces the container's whole overrides object. `overrides` maps a content type id to a policy, and only content types filed in the collection with `publicWrite` are accepted. A saved change expires the collection's page cache and emits `content.container.updated` with `changedFields: ["policies"]`. Saving the same overrides again changes nothing and emits nothing.
```json title="PUT /api/@vitnode/forum/admin/content/forum_forums/3/policies"
{ "overrides": { "forum.topic": { "publish": "approve" } } }
```
### Policy report [#policy-report]
| Name | Type | Description |
| ----------------------------- | -------------------------------------- | ---------------------------------------------------------------------- |
| `id` | `number` | The container |
| `overrides` | `Record` | What this container sets itself |
| `contentTypes[].contentTypeId` | `string` | A content type filed in the collection with `publicWrite` |
| `contentTypes[].pluginId` | `string` | Its plugin |
| `contentTypes[].effective` | full policy | What applies in this container |
| `contentTypes[].inherited` | full policy | What would apply without this container's own overrides |
| `contentTypes[].sources` | `Record` | Where each effective value comes from |
A source is `{ kind: "container", containerId }`, `{ kind: "contentType" }`, `{ kind: "default" }` or `{ kind: "fallback" }`.
### Errors [#errors]
Errors answer `{ code, message }`:
| Status | `code` | When |
| ------ | --------------- | ------------------------------------------------------------------------------------- |
| `400` | `invalidInput` | The body breaks the schema: an unknown key, a value outside the enum, minutes out of range |
| `400` | `invalidPolicy` | `overrides` names a content type that is not filed in the collection |
| `403` | | Missing the admin permission |
| `404` | `notFound` | No such container in this collection |
## Definition errors [#definition-errors]
`defineContentContainer` throws a `ContentEngineError` when the module loads:
| Cause | Message starts with |
| --------------------------------------------- | --------------------------------------------------------------------------- |
| `policies` is not an object or `false` | ``policies is an object with `defaults` and `contentTypes`, or `false`.`` |
| An unknown key beside `defaults` and `contentTypes` | `policies.x is not an option.` |
| A `contentTypes` key that is not `plugin.entity` | `policies.contentTypes has the key "x", which is not a content type id` |
| An unknown policy key | `policies.defaults.x is not a policy.` |
| A value outside the allowed ones | `policies.defaults.publish is not valid:` |
## Server helpers [#server-helpers]
From `@vitnode/core/content` (browser-safe):
| Function | Returns | Behavior |
| --------------------------------------------------------------- | ---------------------------------------- | -------------------------------------------------------------- |
| `resolveContentContainerPolicy({ chain, contentTypeId, fallback, policies })` | `{ policy, sources }` | The pure resolution above. `chain` is the container, then its ancestors, nearest first |
| `contentContainerPolicyFallback(definition)` | `ContentContainerPolicy` | The fallback for one content type |
| `contentAuthorMayEdit(policy, createdAt, now?)` | `boolean` | Whether the owner may still edit |
From `@vitnode/core/content/server`:
| Function | Returns | Behavior |
| ------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------- |
| `resolveContentRowContainer(c, db, definition, row)` | `ContentRecordContainer \| null` | The container an existing row is filed in, with its ancestor chain |
| `resolveContentWriteContainer(c, db, definition, values)` | `ContentRecordContainer \| null` | The container a new record would be filed in |
| `effectiveContentPolicy(definition, container)` | `EffectiveContentContainerPolicy \| null` | `null` when the collection has no policies |
| `resolveContentPublicationPolicy({ actor, c, container, definition, operation: "create", pluginId })` | `{ approval, policy, status }` | How a member's new record is published. Throws `moderators_only` when creating is not allowed |
| `canModerateContent(c, { container, definition, permission, pluginId })` | `Promise` | Checks a moderator permission against the container's scope |
The container service from `createContentContainerService` has `policies(id)` and `updatePolicies(id, overrides)`, the same calls the routes make.
# Publishing rules (/docs/content-engine/container-policies)
Publishing policies let each container decide how members post in it: who may start, whether new records go live or wait for a moderator, whether edits to live records wait too, and how long authors may edit. One forum can be a free-for-all while the one next to it reviews every post.
This guide uses the Forum plugin: the `forum.forums` container collection, with topics (`forum.topic`) filed into forums and comments (`forum.comment`) living in their topic's forum.
## Before you begin [#before-you-begin]
You need a [container collection](/docs/content-engine/containers) and at least one content type with [public write](/docs/content-engine/public-write) filed into it, through `field.container()` or a [`field.relation({ container: true })`](/docs/content-engine/fields#relation). Policies only govern the public write routes. Staff working in the AdminCP are not affected.
### Turn on policies for the collection [#turn-on-policies-for-the-collection]
Add `policies` to the collection's definition. `defaults` applies to every content type in it, and `contentTypes` overrides it for one content type:
```ts title="plugins/forum/src/content/forums.ts"
import { defineContentContainer, field } from "@vitnode/core/content";
export const forumContainers = defineContentContainer({
id: "forum.forums",
fields: {
description: field.textarea({ maxLength: 500, nullable: true }),
},
hierarchy: { maxDepth: 4 },
// [!code ++:10]
policies: {
defaults: {
publish: "immediate",
edits: "immediate",
authorEdit: "always",
},
contentTypes: {
"forum.comment": { authorEdit: "window", authorEditMinutes: 30 },
},
},
publicApi: { path: "forums", fields: ["description"] },
admin: { path: "forum/forums" },
});
```
Topics go live straight away and stay editable by their authors. Comments go live too, but their authors can only edit them for 30 minutes.
`policies: {}` is enough to switch the feature on and leave every decision to the AdminCP. Without `policies`, the collection does not take part: its content types keep using `publicWrite.create.status`, owners edit forever, and `can_edit` stays unscoped.
### Save [#save]
Policies are stored in a column core already has, so there is no migration. `pnpm dev` picks up the change when you save.
Turning policies on also gives each content type in the collection container-scoped `can_edit` and `can_approve` moderator permissions. Grant and label them as described in [Container-scoped permissions](/docs/dev/moderation/scoped-permissions#container-scoped-permissions).
### Override one container in the AdminCP [#override-one-container-in-the-admincp]
Open the collection's screen, such as `/admin/containers/forum/forums`. In a forum's row menu, choose **Publishing**. The **Publishing rules** sheet has one section per content type, with these settings:
| Setting | Key | Choices |
| ---------------------------- | ------------------- | ----------------------------------------------------------- |
| **Who can start** | `create` | **Members**, **Moderators only** |
| **New posts** | `publish` | **Publish immediately**, **Wait for approval** |
| **Edits to published posts** | `edits` | **Apply immediately**, **Wait for approval** |
| **Author editing** | `authorEdit` | **Always**, **Never**, **For a limited time** |
| **Editing window** | `authorEditMinutes` | Minutes, used by **For a limited time** |
{/* Image prompt: AdminCP Publishing rules sheet for the forum "Help", with a Topics section where New posts is set to Wait for approval and the other settings show "Inherit (currently: ...)" with a line under each saying where the value comes from, and a Save rules button in the footer */}
Every setting starts on **Inherit (currently: …)**, and the line below it says where the current value comes from: a parent forum, the collection's defaults or the content type's own default. For the "Help" forum, set **New posts** to **Wait for approval** for topics and choose **Save rules**.
The sheet needs the collection's `can_view` admin permission to open and `can_edit` to save. Saving emits `content.container.updated` with `changedFields: ["policies"]`.
## How a value is chosen [#how-a-value-is-chosen]
Each of the five keys is decided on its own. The engine takes the first layer that sets it:
1. the record's container, for that content type;
2. the nearest ancestor that sets it, walking up the parents;
3. `policies.contentTypes[contentTypeId]` in the definition;
4. `policies.defaults` in the definition;
5. the fallback: `create: "members"`, `publish` from `publicWrite.create.status` (`"published"` becomes `"immediate"`, `"draft"` becomes `"approve"`), `edits: "immediate"`, `authorEdit: "always"`, `authorEditMinutes: 60`.
With "Help" set to **Wait for approval** for topics, a topic in its child forum "Bug reports" waits for approval too, while comments there still publish immediately: rules are per content type, and nobody changed the comment rules.
A key that is absent inherits. An explicit value is an override, even when it matches the parent today. If someone later relaxes "Help", a child that explicitly says **Wait for approval** keeps waiting. Choose **Inherit** to remove an override.
## What members notice [#what-members-notice]
| Rule | What happens on the public write routes |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `publish: "approve"` | A new record is stored as a draft, a submission opens, and the response carries `approval`. See [Approvals](/docs/content-engine/approvals) |
| `edits: "approve"` | An author's edit of a published record becomes a proposal. The live record does not change until a moderator approves |
| `authorEdit: "never"` | Only moderators edit. The author gets `403` with the `edit_window_closed` issue |
| `authorEdit: "window"` | The author edits until `authorEditMinutes` after the record's server `createdAt`, then gets `403` with `edit_window_closed` |
| `create: "moderators"` | Only moderators holding `can_edit` in that container may create. Everyone else gets `403` with the `moderators_only` issue |
Moderators are never held back by these rules. A `can_edit` holder edits any record in the container at any age, and a `can_approve` holder skips approval for their own posts. Root roles pass every check. The issue codes come in the usual [rejection](/docs/content-engine/public-write-api#rejection) body, so translate them like any other issue.
Changing a policy never touches submissions that are already pending.
## Check the result [#check-the-result]
Sign in as a regular member and create a topic in "Help". The response is a draft waiting for approval:
```json title="POST /api/@vitnode/forum/content/topics → 201"
{
"approval": {
"id": 7,
"kind": "create",
"reason": null,
"status": "pending",
"submittedAt": "2026-10-13T09:12:44.512Z",
"values": null
},
"id": 42,
"slug": "the-editor-forgets-my-draft",
"status": "draft",
"publishedAt": null,
"version": 1,
"values": { "title": "The editor forgets my draft", "body": { "type": "doc", "content": [] }, "forum": 3 }
}
```
The topic is not on the public site yet. It appears in the [ModCP approval queue](/docs/dev/moderation/review-approvals) for moderators who hold `can_approve` in "Help". A topic in a forum without overrides still answers with `"status": "published"` and `"approval": null`.
Every option, route and error is in the [Publishing policies reference](/docs/content-engine/container-policies-api).
# Containers (/docs/content-engine/containers)
A container is a place a record lives in: one forum board, one blog section, one knowledge-base category. You declare a **collection** of containers once in code, admins build its tree in the AdminCP, and each record of a content type points at exactly one container through `field.container()`.
This guide follows the newsroom plugin, with a `newsroom.desks` collection and letters to the editor (`newsroom.letter`) filed into it.
## Containers or a content type? [#containers-or-a-content-type]
A category could also be a content type with a [relation](/docs/content-engine/relations). Pick a container when the thing organizes content rather than being content itself:
| | Container collection | Content type |
| ------------------- | ------------------------------------------------------------------------- | ----------------------------------------------- |
| Declared with | `defineContentContainer` | `defineContentType` |
| Storage | One shared core table, `core_content_containers`. No migration of its own | Its own table, with a migration |
| Shape | A tree with parents, sibling order and a depth limit | Flat records |
| Fields | A few scalars (`text`, `textarea`, `number`, `boolean`, `enum`) | Every field kind |
| Drafts, revisions | No. A container exists or it does not | Optional `publication`, `editorial` and friends |
| Linked from records | `field.container()`, at most one per content type | `field.relation()`, as many as you need |
| Public filter | `?desk=4`, and `includeDescendants=true` for a whole subtree | `?category=4`, exact match only |
A record belongs to one container. For anything else it points at, such as tags, keep using relations.
## Add a container collection [#add-a-container-collection]
You need a content type to file into containers, like `newsroom.letter` from [Member writing](/docs/content-engine/public-write#add-an-owner-versions-and-the-write-options).
### Define the collection [#define-the-collection]
Create `src/content/desks.ts`. The definition describes the collection, and each desk is a row an admin creates later:
```ts title="plugins/newsroom/src/content/desks.ts"
import { defineContentContainer, field } from "@vitnode/core/content";
export const deskContainers = defineContentContainer({
id: "newsroom.desks",
fields: {
description: field.textarea({ maxLength: 500, nullable: true }),
color: field.text({ maxLength: 7, nullable: true }),
icon: field.text({ maxLength: 64, nullable: true }),
locked: field.boolean({ defaultValue: false }),
},
hierarchy: { maxDepth: 3 },
ordering: { mode: "manual" },
publicApi: {
path: "desks",
fields: ["description", "color", "icon"],
},
admin: { path: "newsroom/desks" },
});
```
Every container already has `id`, `parentId`, `name`, `slug`, `position` and `depth`. `fields` adds your own values, stored in a `metadata` column and validated against the definition on every write. `locked` is not in `publicApi.fields`, so it never leaves the server.
| Name | Type | Required | Default | Description |
| ----------- | ------------------------------------------- | -------- | -------------------------------- | ----------------------------------------------------------------------------------------------- |
| `id` | `string` | Yes | | `plugin.collection`, lowercase and dot separated. Every row stores it, so never rename it |
| `fields` | `field.*()` map | No | `{}` | Extra values per container. `text`, `textarea`, `number`, `boolean` and `enum` only |
| `hierarchy` | `{ enabled?: boolean; maxDepth?: number }` | No | `{ enabled: true, maxDepth: 5 }` | `maxDepth` counts levels, roots included, from 2 to 10. `enabled: false` makes a flat list |
| `ordering` | `{ mode?: "manual" \| "alphabetical" }` | No | `{ mode: "manual" }` | How siblings are sorted. See [Hierarchy and ordering](/docs/content-engine/container-hierarchy) |
| `publicApi` | `{ path: string; fields?: string[] }` | No | off | Read-only public routes at `/api/{pluginId}/content/{path}` |
| `admin` | `{ path?; permissionModule?; navigation? }` | No | see below | The AdminCP screen and its staff permissions |
| `policies` | `{ defaults?; contentTypes? }` \| `false` | No | off | Per-container publishing rules. See [Publishing rules](/docs/content-engine/container-policies) |
`admin.path` defaults to the id with dots turned into slashes (`newsroom/desks`), so the screen opens at `/admin/containers/newsroom/desks`. `admin.permissionModule` defaults to the snake-cased id (`newsroom_desks`), and `admin.navigation: false` hides the sidebar entry.
### Point the content type at it [#point-the-content-type-at-it]
Add one `field.container()` to the content type. List it in `publicApi.fields` to return it, in `filterableFields` to filter by it, and in `publicWrite.create.fields` to let members pick it:
```ts title="plugins/newsroom/src/content/letter.ts (excerpt)"
import { deskContainers } from "@/content/desks"; // [!code ++]
export const letterContentType = defineContentType({
id: "newsroom.letter",
tableName: "newsroom_letters",
fields: {
title: field.text({ required: true, minLength: 3, maxLength: 200 }),
slug: field.slug({ source: "title" }),
body: field.richText({ required: true }),
author: field.user(),
desk: field.container({ definition: deskContainers, required: true }), // [!code ++]
},
publicApi: {
path: "letters",
fields: ["id", "title", "slug", "body", "desk", "publishedAt"], // [!code highlight]
filterableFields: ["desk"], // [!code ++]
},
publicWrite: {
ownership: { field: "author" },
create: { fields: ["title", "body", "desk"], status: "published" }, // [!code highlight]
update: { fields: ["title", "body"] },
},
});
```
The column is an `integer` foreign key to `core_content_containers.id` with `ON DELETE RESTRICT`, plus an index on `(desk, publishedAt)`. Every write checks that the id belongs to `newsroom.desks`, not just that it exists. All options are in [Fields](/docs/content-engine/fields#container).
A content type can also live in the container of a record it points at, such as a reply in its topic's forum, with a required `field.relation({ target, container: true })` instead of a `field.container()`. See [Comments](/docs/content-engine/threads).
### Register the collection on the API [#register-the-collection-on-the-api]
Pass the definition to both content modules. The admin module adds the staff routes and the `newsroom_desks` permissions, and the public module adds the read routes. The newsroom registers more content types than shown here:
```ts title="plugins/newsroom/src/api/modules/admin/admin.module.ts (excerpt)"
import { deskContainers } from "@/content/desks"; // [!code ++]
buildContentAdminModule({
containers: [deskContainers], // [!code ++]
contentTypes: [storyContent, letterContent],
}),
```
```ts title="plugins/newsroom/src/config.api.ts (excerpt)"
buildContentPublicModule({
containers: [deskContainers], // [!code ++]
contentTypes: [storyContent, letterContent],
}),
```
A content type whose `field.container()` names a collection no plugin registers stops the API at startup. Registering the same definition object in both modules is fine.
### Register the AdminCP screen [#register-the-admincp-screen]
Add the collection to `containers` in both AdminCP files, next to your content types. `icon` is optional and defaults to a folder icon:
```tsx title="plugins/newsroom/src/admin/nav.tsx (excerpt)"
import { FolderTreeIcon, MailIcon, NotebookPenIcon } from "lucide-react"; // [!code highlight]
import { deskContainers } from "@/content/desks"; // [!code ++]
export const adminNav = {
pluginId: manifest.id,
containers: [{ definition: deskContainers, icon: }], // [!code ++]
contentTypes: [
{ definition: storyContentType, icon: },
{ definition: letterContentType, icon: },
],
} satisfies AdminNavPluginSource;
```
The newsroom's AdminCP sources hold nothing server-only, so its `admin/content.tsx` reuses the same object:
```tsx title="plugins/newsroom/src/admin/content.tsx"
export { adminNav as adminContent } from "./nav";
```
[Plugin files](/docs/content-engine/plugin-files) explains why the two files are separate.
### Add the labels [#add-the-labels]
The AdminCP reads the collection's names from `{pluginId}.containers.{entity}`, where the entity is the id without its plugin prefix. The permission labels follow the permission module:
```json title="plugins/newsroom/src/locales/en.json (excerpt)"
{
"newsroom": {
"containers": {
"desks": {
"label": "{count, plural, one {Desk} other {Desks}}",
"title": "Desks",
"desc": "The desks readers send their letters to. Drag to reorder or nest desks.",
"fields": {
"description": "Description",
"color": "Color",
"icon": "Icon",
"locked": "Locked"
}
}
},
"content": {
"letter": { "fields": { "desk": "Desk" } }
}
},
"newsroom:newsroom_desks": "Desks",
"newsroom:newsroom_desks:can_view": "View desks",
"newsroom:newsroom_desks:can_create": "Create desks",
"newsroom:newsroom_desks:can_edit": "Edit and move desks",
"newsroom:newsroom_desks:can_delete": "Delete desks"
}
```
Without labels, the screen falls back to a name derived from the id, such as "Desks".
### Migrate [#migrate]
Run this from the workspace root while `pnpm dev` is running:
```bash tab="bun"
bun run db:migrate
```
```bash tab="pnpm"
pnpm db:migrate
```
```bash tab="npm"
npm run db:migrate
```
The collection itself needs no table, because every definition shares `core_content_containers`. The migration only adds the `desk` column to `newsroom_letters`.
A required container field becomes a `NOT NULL` column. If the table already
has rows, edit the generated migration to create a container and assign it
before the `SET NOT NULL`. [Migrations](/docs/content-engine/database) covers
editing migrations.
## Manage containers in the AdminCP [#manage-containers-in-the-admincp]
Open **AdminCP → Newsroom → Desks** (`/admin/containers/newsroom/desks`). Staff need the collection's `can_view` permission to see it, and `can_create`, `can_edit` or `can_delete` for each action.
- **The tree** shows every desk with its children nested below it. Drag a desk to reorder it among its siblings or to drop it inside another desk.
- **Create and edit** open a sheet with the name, the slug and the collection's own fields. A container created without a slug gets one derived from its name.
- **The move menu** on each row does the same as dragging from the keyboard: **Move up**, **Move down**, **Move to top level** and **Move inside…**.
- **Delete** works only on an empty desk. A desk with child desks or with letters is refused with a message that says which one, and nothing changes.
In a content type's generated form, a container field becomes a **picker** that lists the collection's tree, so staff can file a letter into a desk or move it to another one.
A drag that breaks a rule, such as nesting a desk deeper than `maxDepth` or dropping it inside its own child, is refused the same way. [Hierarchy and ordering](/docs/content-engine/container-hierarchy) lists every rule.
## Check the result [#check-the-result]
Create a "Politics" desk with an "Elections" desk inside it, then read the public tree:
```bash
curl http://localhost:3000/api/newsroom/content/desks
```
```json
{
"items": [
{
"id": 1,
"parentId": null,
"name": "Politics",
"slug": "politics",
"position": 0,
"depth": 1,
"metadata": {
"description": "Parliament, parties and policy",
"color": "#2563eb",
"icon": null
}
},
{
"id": 2,
"parentId": 1,
"name": "Elections",
"slug": "elections",
"position": 0,
"depth": 2,
"metadata": { "description": null, "color": null, "icon": null }
}
]
}
```
Items come in tree order: each parent, then its subtree. `metadata` holds only `publicApi.fields`, and a value nobody set is `null`. [Container pages](/docs/content-engine/container-frontend) turns this into pages.
## Definition errors [#definition-errors]
`defineContentContainer` and the boot checks throw a `ContentEngineError` before the app serves a request:
| Cause | Message starts with |
| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| An id that is not `plugin.collection` | `Container definition id "x" must look like "plugin.collection"` |
| A field named `id`, `name`, `slug`, `depth`, `metadata` or another column | `Field "x" is reserved.` |
| A field kind other than text, textarea, number, boolean or enum | `Field "x" is a "relation" field.` |
| A field with `localized`, `unique` or `ai` | `Field "x" is` followed by the option and why containers refuse it |
| `maxDepth` below 2 or above 10 | `hierarchy.maxDepth must be a whole number from 2 to 10.` |
| `publicApi.fields` naming an unknown or built-in field | `publicApi.fields references unknown field "x".` |
| Two collections with one id or one `admin.path` | `Duplicate container definition id` / `AdminCP path "x" is claimed by both` |
| A collection and a content type sharing a public path or permission module | `Public path "x" is claimed by both` / `Permission module "x" is used by both` |
| Two `field.container()` in one content type | `Content type declares 2 container fields` |
| `field.container()` pointing at an unregistered collection | `Field "x" uses the container collection "y", which no plugin registers.` |
| A container field in `publicWrite.update.fields` | `publicWrite.update.fields includes the container field "x".` |
## Related [#related]
- [Hierarchy and ordering](/docs/content-engine/container-hierarchy): depth, moves, safe deletion and the server-side service.
- [Container pages](/docs/content-engine/container-frontend): a desk tree, a desk page and a create form with a desk picker.
- [Publishing rules](/docs/content-engine/container-policies): who may post in each desk, whether posts wait for [approval](/docs/content-engine/approvals), and how long authors may edit.
Read permissions per container, such as desks hidden from guests, are not available yet. Today every reader sees every container in the public tree.
# Visibility (/docs/content-engine/content-visibility)
Hiding takes a record off the public site right away while it stays published. It disappears from the public API, its page, search and the sitemap, and unhiding brings it back with its original URL and publish date. Reach for it when a post has to go now and the questions can wait. This guide follows the blog plugin, whose articles can be hidden.
| You want to | Use |
| ---------------------------------------------------------------------- | --------------------------------------------------------------- |
| Take a record down for now and put it back as it was | Hide |
| Turn a record back into a draft to rework it before it goes live again | [Unpublish](/docs/content-engine/publication) |
| Remove it for good | Delete |
## Before you begin [#before-you-begin]
Hiding needs [`publication`](/docs/content-engine/public-api), because a record that is never public has nothing to hide from.
### Turn on visibility [#turn-on-visibility]
The blog's article content type turns it on next to `publication`:
```ts title="plugins/blog/src/content/post.ts"
export const blogPostContentType = defineContentType({
id: "blog.post",
tableName: "blog_posts",
publication: true,
visibility: true, // [!code ++]
// ...
});
```
`visibility` takes only `true` or `false`. Without `publication` it throws when the content type is defined. With it, `hiddenAt`, `hiddenBy` and `visibility` are reserved and cannot be field names.
### Build and migrate [#build-and-migrate]
Run `pnpm db:migrate`. The migration adds two nullable columns to the main table. For the blog, `apps/api/migrations/20261011093549_content_visibility_id_strategies` contains:
```sql title="migration.sql (excerpt)"
ALTER TABLE "blog_posts" ADD COLUMN "hiddenAt" timestamp;
ALTER TABLE "blog_posts" ADD COLUMN "hiddenBy" integer;
CREATE INDEX "blog_posts_hidden_by_idx" ON "blog_posts" ("hiddenBy");
ALTER TABLE "blog_posts" ADD CONSTRAINT "blog_posts_hiddenBy_core_users_id_fkey" FOREIGN KEY ("hiddenBy") REFERENCES "core_users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
```
Existing records stay visible. `hiddenAt` is when the record was hidden and `hiddenBy` is the staff member who hid it. A later migration adds a third nullable column, `hiddenReason` (up to 500 characters), for the optional note left when hiding from the site.
### Label the permission [#label-the-permission]
Visibility adds a `can_hide` permission, separate from `can_publish`, so a moderator can take records down without being able to publish. The blog labels it next to its other article permissions:
```json title="plugins/blog/src/locales/en.json"
{
"@vitnode/blog:posts:can_hide": "Hide and unhide articles"
}
```
Grant it to the staff who should moderate in **AdminCP → Staff**.
### Hide an article [#hide-an-article]
Open **AdminCP → Blog → Articles**, open the **More actions** menu of a published article and choose **Hide**. Confirm with **Yes, hide it**:
A toast says the article is now hidden. The row keeps its **Published** badge, and its title gets an eye-off icon in front with an **Article hidden** tooltip. The **Visibility** filter in the list toolbar shows only hidden or only visible records, and it combines with the **Status** filter:
The edit page shows the same icon before the title, an **Unhide** action (in the blog's editor, it lives in the ▾ menu next to **Save changes**) and a note that publishing a hidden record does not make it public:
Choose **Unhide** in the same menu, or on the edit page, to bring the article back. In the database, hiding sets `blog_posts."hiddenAt"` and `"hiddenBy"`, and unhiding clears both, along with `"hiddenReason"`.
Cleaning up after a spam wave? Tick several articles and choose **Visibility → Hide** in the floating bar. The menu counts how many of them are still visible, such as **Hide 2 of 3**, and leaves the rest alone. **Unhide** works the same way. See [Bulk actions](/docs/content-engine/admincp#bulk-actions).
## What hiding does [#what-hiding-does]
A record is public only when it is published, its `publishedAt` is not in the future, and it is not hidden. While a record is hidden:
- The public API list leaves it out for everybody but the [people who can still see it](#who-can-still-see-it), and its detail route answers `404`, in every language, including a language that falls back to the default one.
- Its [page](/docs/content-engine/public-pages) answers `404`, and so do its old slugs instead of redirecting.
- The [sitemap](/docs/content-engine/seo#sitemap) and other pages' `hreflang` alternates leave it out, and [site search](/docs/content-engine/search) marks its document private.
- Signed [preview links](/docs/content-engine/editorial-previews) still work, and the AdminCP still shows it.
## Who can still see it [#who-can-still-see-it]
Hidden doesn't mean gone for the people working on it. Signed in, a record's **authors**, its **editors** and its **moderators** still reach it:
- **Authors** are the users in the content type's [`search.authorField`](/docs/content-engine/search), such as the blog's **Author** field. Without one, the [public write](/docs/content-engine/public-write) owner is the author.
- **Editors** are staff with `can_edit` on the content type, such as `posts:can_edit` for the blog.
- **Moderators** with the moderator permission `can_view_hidden` on a [reportable](/docs/dev/moderation/enable-reports) content type, in the record's scope when it has one. They need no AdminCP permission.
The route tells whose record it is by its `id`, so `id` must be in `publicApi.fields`. For them:
- The page opens with an eye-off icon before the title and a **This article is hidden** note, so nobody mistakes it for a live page. The response sends `noindex` and `Cache-Control: private, no-store`, so search engines and caches never keep it.
- The detail route answers `200`, and `GET .../delivery/resolve/{slug}` returns `hidden: true` plus the record's own published translations in `alternates`, so the language switcher opens the same article in another language at its own slug.
- The public list, such as `/blog`, shows it among the published records with the eye-off icon before its title. API rows carry `hidden: true`, and the response is `Cache-Control: private, no-store`.
- [Site search](/docs/content-engine/search) and the member timeline list it with the eye-off icon before its title and a tooltip like **Article hidden**.
On a list, moderators see every hidden record only when the content type has no moderation scope. With a scope, the list shows them what they authored or can edit, and the page itself still opens for them.
Everyone else, signed in or not, still gets a `404`. Old slugs never redirect to a hidden record, and the list, sitemap and other pages' `hreflang` alternates leave it out for everybody.
Search learns that a record is hidden when it is hidden or unhidden. Records hidden before you updated VitNode show up for their authors and editors only after a reindex: **Debug Panel → Search** (`/admin/core/debug/search`), then **Reindex** on the collection, such as `blog.post`. See [Search](/docs/content-engine/search).
Hiding changes nothing else. `status` and `publishedAt` stay as they are, so unhiding a published record puts it back with its original date. Publishing, unpublishing and scheduled publishes never change visibility, so publishing a hidden record keeps it off the site until someone unhides it. Restoring a revision never changes visibility either.
With [`editorial`](/docs/content-engine/editorial), hiding and unhiding raise the record's `version` and store a revision, shown as **Hidden** or **Unhidden** in the history. Hiding a record that is already hidden changes nothing: no write, no revision and no event.
Hiding is per record. To take one language off the site, unpublish that translation instead.
## Hide from the API [#hide-from-the-api]
The admin module has `POST /{id}/hide` and `POST /{id}/unhide`, such as `POST /api/@vitnode/blog/admin/content/posts/703/hide` for the blog. Both need `can_hide` and accept an optional body:
```json
{ "expectedVersion": 4 }
```
With `expectedVersion`, the call fails with `409` and `CONTENT_VERSION_CONFLICT` when someone saved the record meanwhile, like any [editorial write](/docs/content-engine/editorial#safe-concurrent-edits). Both routes answer `200` with `{ changed, row }`, where `changed` is `false` when the record was already in that state. A malformed id is `400` and a missing record is `404`. With `delivery.redirects`, unhiding can also fail with `409` when another record took the URL while this one was hidden.
The admin list route accepts `?visibility=hidden` or `?visibility=visible`, and it combines with `?status=`.
From your own code, `hide(id, options)` and `unhide(id, options)` exist on the services when visibility is on. See [Services](/docs/content-engine/services#save-like-the-admincp).
## Show it on your pages [#show-it-on-your-pages]
The people who still see a hidden record should know readers don't. Tell them on the page:
- **A page with [delivery](/docs/content-engine/public-pages)** reads `metadata.hidden` from `contentDeliveryPage`. The blog shows an eye-off icon before the title and a notice, and drops the Report button.
- **A page without delivery** reads the `X-Content-Hidden` header of `GET /{slug}`, which is `"true"` only for a hidden record:
```tsx title="plugins/newsroom/src/pages/letter-page.tsx (excerpt)"
import { CONTENT_HIDDEN_HEADER } from "@vitnode/core/content";
const detail = await fetcher({
plugin: manifest.id,
method: "get",
module: "content/letters",
path: "/{slug}",
args: { params: { slug: encodeURIComponent(slug) } },
});
// Only the author and moderators get a hidden letter; readers get 404.
const hidden = detail.headers.get(CONTENT_HIDDEN_HEADER) === "true";
// The loader returns `hidden` with the letter, and the page reads it:
{item.hidden ? (
} variant="warning">
{t("hidden.title")}{t("hidden.desc")}
) : null}
```
[`useContentPermissions`](/docs/content-engine/public-permissions) already answers `canReport: false` for a hidden record, and `canEdit: false` for its author, so the page needs no extra checks for its buttons. A moderator can still edit it.
## Delete, hide, unpublish or reject [#delete-hide-unpublish-or-reject]
The public site creates and edits; it never deletes or hides. These actions belong to staff:
| Action | Readers afterwards | Who, and where |
| --------------- | --------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Hide | `404`; authors and moderators still see it | Staff with `can_hide` in the AdminCP, or moderators acting on a [report](/docs/dev/moderation/process-reports) |
| Unpublish | `404`; the record is a draft again | Staff with `can_publish`, in the AdminCP |
| Reject approval | A new record stays a draft; a proposed edit never applies | Moderators with `can_approve`, in the [approvals queue](/docs/dev/moderation/review-approvals) |
| Delete | Gone for good, with its URL | Staff with `can_delete`, in the [AdminCP](/docs/content-engine/admincp#bulk-actions) |
Hiding is the reversible one. The record keeps its revisions, its reports and its place in a thread. There is no public delete route, so don't put a Delete button on a public page.
## Events and caches [#events-and-caches]
A hide emits `content.blog.post.hidden` with `{ actorUserId, contentId, hiddenAt }`, and an unhide emits `unhidden` with `{ actorUserId, contentId }`. Both update the search index and the delivery data. See [Events](/docs/content-engine/events).
Front ends listed in [`content.revalidateOrigins`](/docs/content-engine/caching#notify-a-separate-front-end) are notified at once when a hide or unhide changes what the public can see. Hiding a draft notifies nobody, because nothing public changed.
## Check the result [#check-the-result]
Hide the published "Second post", then request its page and its API entry:
```bash
curl -o /dev/null -w "%{http_code}\n" "http://localhost:3000/blog/article/second-post"
curl -o /dev/null -w "%{http_code}\n" "http://localhost:3000/api/@vitnode/blog/content/blog/article/second-post"
```
Both answer `404`, like a draft, and the article drops out of the blog list and the sitemap. In the AdminCP it is still **Published**. Unhide it, and the same requests answer `200` with the original `publishedAt`. Open `/blog` and the page while signed in as one of its authors, and the list shows it with the eye-off icon and the page loads with the hidden note.
The newsroom plugin's letters to the editor show the same note through the header. Ada Lovelace opens their own hidden letter, and only they and the moderators can:
# First content type (/docs/content-engine/create-a-content-type)
This tutorial starts a small newsroom with one **article** content type, which has a title, a slug and a body. By the end, staff create and edit articles in the AdminCP, and you have the table, the staff API and the staff permissions without writing any of them by hand.
The next tutorials keep building the same article: [Drafts & publishing](/docs/content-engine/publication), [Public API](/docs/content-engine/public-api), [Content list](/docs/content-engine/public-lists) and [Content page](/docs/content-engine/public-pages).
## Before you begin [#before-you-begin]
You need a plugin your app already loads. This tutorial uses one named `newsroom`, made with [Create a plugin](/docs/dev/plugins/create), so its plugin id is `newsroom` and its files live in `plugins/newsroom/`. Use your own plugin's name wherever you see `newsroom`. You also need a running PostgreSQL database and an AdminCP account.
### Bind the Content Engine builders [#bind-the-content-engine-builders]
Edit `src/api/builders.ts`. The generated file binds the API builders. Add the Content Engine ones next to them, so no file in your plugin has to spell out its plugin id:
```ts title="plugins/newsroom/src/api/builders.ts"
import { bindApiPlugin } from "@vitnode/core/api/lib/bind-api-plugin";
import { bindContentPlugin } from "@vitnode/core/content/server"; // [!code ++]
import { manifest } from "@/manifest.gen";
const apiBuilders = bindApiPlugin(manifest);
export const buildModule = apiBuilders.buildModule;
export const buildRoute = apiBuilders.buildRoute;
// [!code ++:6]
const contentBuilders = bindContentPlugin(manifest);
export const buildContentAdminModule =
contentBuilders.buildContentAdminModule;
export const buildContentPublicModule =
contentBuilders.buildContentPublicModule;
```
`vitnode dev` and `vitnode build` write `src/manifest.gen.ts` from your `package.json`, and `manifest.id` is the plugin id.
### Define the article [#define-the-article]
Create `src/content/article.ts`. This is the complete file:
```ts title="plugins/newsroom/src/content/article.ts"
import { defineContentType, field } from "@vitnode/core/content";
export const articleContentType = defineContentType({
id: "newsroom.article",
tableName: "newsroom_articles",
fields: {
title: field.text({ required: true, minLength: 3, maxLength: 200 }),
slug: field.slug({ source: "title" }),
body: field.richText({ required: true }),
},
admin: {
path: "newsroom/articles",
titleField: "title",
list: {
columns: ["title", "slug", "updatedAt"],
orderableFields: ["title"],
},
},
});
```
- `id` is `plugin.entity`. The part after the dot, `article`, names the translations and the permissions.
- `tableName` is the Postgres table.
- The engine fills `slug` from the title when you leave it empty, and keeps it when the title changes later, so links keep working.
- `body` is [rich text](/docs/content-engine/rich-text). The AdminCP shows an editor, and the database stores a JSON document.
- `admin.path` puts the screen at `/admin/content/newsroom/articles`. `list.columns` may name your fields and the system columns `id`, `createdAt` and `updatedAt`.
[Fields](/docs/content-engine/fields) lists every field helper.
### Create the model [#create-the-model]
Create `src/database/articles.ts`. `createContentModel` turns the definition into a Drizzle table, validation schemas and a service:
```ts title="plugins/newsroom/src/database/articles.ts"
import { createContentModel } from "@vitnode/core/content/server";
import { articleContentType } from "@/content/article";
export const articleContent = createContentModel(articleContentType);
export const newsroom_articles = articleContent.table;
```
Export the table. Migrations find tables through the exports of your plugin's built `src/database/*.js` files, so a table nobody exports never gets created.
### Register the staff API routes [#register-the-staff-api-routes]
Create `src/api/modules/admin/admin.module.ts`:
```ts title="plugins/newsroom/src/api/modules/admin/admin.module.ts"
import { buildContentAdminModule, buildModule } from "@/api/builders";
import { articleContent } from "@/database/articles";
export const adminModule = buildModule({
name: "admin",
routes: [],
modules: [buildContentAdminModule({ contentTypes: [articleContent] })],
});
```
Then add it to the plugin's API. This is an excerpt of `src/config.api.ts`:
```ts title="plugins/newsroom/src/config.api.ts"
import { adminModule } from "./api/modules/admin/admin.module"; // [!code ++]
import { helloModule } from "./api/modules/hello/hello.module";
export const newsroomApiPlugin = () =>
buildApiPlugin({
manifest,
modules: [helloModule, adminModule], // [!code highlight]
});
```
The routes live under `/api/newsroom/admin/content/article` and answer only staff signed in to the AdminCP. Keep the module named `admin`, because the API checks the AdminCP session on paths that contain `/admin/`.
### Add the AdminCP screen [#add-the-admincp-screen]
Create `src/admin/nav.tsx` with the sidebar link:
```tsx title="plugins/newsroom/src/admin/nav.tsx"
import { NewspaperIcon } from "lucide-react";
import { articleContentType } from "@/content/article";
import { manifest } from "@/manifest.gen";
export const adminNav = {
pluginId: manifest.id,
contentTypes: [{ definition: articleContentType, icon: }],
};
```
Create `src/admin/content.tsx` and reuse the same list for the screen:
```tsx title="plugins/newsroom/src/admin/content.tsx"
export { adminNav as adminContent } from "./nav";
```
VitNode finds both files by their names and exports. They are separate because the sidebar loads on every AdminCP page, while the screen and its forms load only when someone opens it. [AdminCP](/docs/content-engine/admincp) shows how to customize the list and the form later.
### Add the labels [#add-the-labels]
Edit `src/locales/en.json`. The `home` keys came with the generated plugin. Add everything else:
```json title="plugins/newsroom/src/locales/en.json"
{
"newsroom": {
"home": {
"api": "Your plugin's API answered:",
"desc": "This page ships inside the plugin and is served by the app that installed it.",
"title": "Hello from your plugin"
},
"title": "Newsroom",
"content": {
"article": {
"label": "{count, plural, one {Article} other {Articles}}",
"title": "Articles",
"desc": "News and updates for your community.",
"fields": {
"title": "Title",
"slug": "Slug",
"body": "Body",
"updatedAt": "Updated"
}
}
}
},
"newsroom:article": "Articles",
"newsroom:article:can_view": "View articles",
"newsroom:article:can_create": "Create articles",
"newsroom:article:can_edit": "Edit articles",
"newsroom:article:can_delete": "Delete articles"
}
```
- `title` names the sidebar group. Under `content.article`, buttons such as **Create Article** use `label`, and `title` and `desc` head the list.
- The `newsroom:article:*` keys label the four staff permissions the Content Engine generated. A missing key shows the raw permission id.
### Build and migrate [#build-and-migrate]
Run these from the workspace root. `db:migrate` reads your plugin's built files, so build first:
```bash tab="bun"
bun run build:plugins
bun run db:migrate
```
```bash tab="pnpm"
pnpm build:plugins
pnpm db:migrate
```
```bash tab="npm"
npm run build:plugins
npm run db:migrate
```
While `pnpm dev` runs, it rebuilds the plugin on every save, so `db:migrate` alone is enough. The command writes a migration to `apps/api/migrations/` and applies it:
```sql title="apps/api/migrations/_/migration.sql"
CREATE TABLE "newsroom_articles" (
"id" serial PRIMARY KEY,
"createdAt" timestamp DEFAULT now() NOT NULL,
"updatedAt" timestamp DEFAULT now() NOT NULL,
"title" varchar(200) NOT NULL,
"slug" varchar(160) NOT NULL,
"body" jsonb NOT NULL
);
CREATE UNIQUE INDEX "newsroom_articles_slug_key" ON "newsroom_articles" ("slug");
```
You declared three fields, and the engine added the `id` and the timestamps. Commit the migration with your code. [Migrations](/docs/content-engine/database) covers what else it generates.
### Create an article [#create-an-article]
Start the app with `pnpm dev` and open **AdminCP → Newsroom → Articles**. Click **Create Article**, enter the title `Welcome to the newsroom`, leave **Slug** empty and write a sentence in **Body**:
Click **Create**. A toast confirms it and the list shows the new row with the slug `welcome-to-the-newsroom`. Create a second article, `Release notes for October`. The next tutorials use both.
## Check the result [#check-the-result]
- The list shows both articles with the columns from `list.columns`. Click **Title** to sort, or type in the search box.
- Click the pencil on a row, change the body and save. The edit opens the same generated form.
- In **AdminCP → Staff → Administrators**, a restricted administrator now has a **Newsroom → Articles** group with your four permission labels. Every generated route checks them.
Next, keep unfinished articles private with [Drafts & publishing](/docs/content-engine/publication).
# Migrations (/docs/content-engine/database)
Every content type becomes ordinary Postgres tables managed by Drizzle. `createContentModel` from `@vitnode/core/content/server` builds them from the definition, and the usual VitNode migration workflow creates them. Values are stored in typed columns. Only `field.blocks()` and `field.richText()` keep a JSON document, in a `jsonb` column.
## Generate and apply a migration [#generate-and-apply-a-migration]
After you add or change a content type, run this from the workspace root:
```bash tab="bun"
bun run db:migrate
```
```bash tab="pnpm"
pnpm db:migrate
```
```bash tab="npm"
npm run db:migrate
```
1. `db:migrate` reads each plugin's built `dist/` folder. `pnpm dev` rebuilds a plugin every time you save, so while it runs the output is always current. Without `pnpm dev`, such as in CI or right after a checkout, run `pnpm build:plugins` first, or the migration sees the old schema.
2. `db:migrate` compares the exported tables of every plugin in your API config with the last snapshot and writes a new folder to `apps/api/migrations/`.
3. It applies pending migrations, then makes sure the initial data exists.
Commit the generated migration together with the content type. Production never migrates on startup, so run migrations as a deploy step. [Database CLI](/docs/dev/cli/database) covers `vitnode db generate --name ` for a named migration, `vitnode db status` and the rest.
## Export every table [#export-every-table]
Drizzle Kit finds tables by reading the exports of `node_modules//dist/src/database/*.js` for each plugin. A table without an export is left out of the migration, without a warning. A content type with relations, translations and repeatable rows has several tables:
```ts title="plugins/newsroom/src/database/explainers.ts"
import { createContentModel } from "@vitnode/core/content/server";
import { explainerContentType } from "@/content/explainer";
import { newsroom_categories } from "./categories";
import { newsroom_tags } from "./tags";
export const explainerContent = createContentModel(explainerContentType, {
references: {
categories: () => newsroom_categories.id,
tags: () => newsroom_tags.id,
},
});
export const newsroom_explainers = explainerContent.table;
export const newsroom_explainers_translations =
explainerContent.translationTable;
export const newsroom_explainers_categories =
explainerContent.advancedTables.junctions.categories;
export const newsroom_explainers_tags =
explainerContent.advancedTables.junctions.tags;
export const newsroom_explainers_related_explainers =
explainerContent.advancedTables.junctions.relatedExplainers;
export const newsroom_explainers_faq =
explainerContent.advancedTables.repeatables.faq;
```
| Model member | Exists when |
| ------------------------------------ | --------------------------------------------------------- |
| `table` | Always |
| `translationTable` | `localization` is enabled; otherwise `null` |
| `advancedTables.junctions.` | A `relation`, `user` or `file` field has `multiple: true` |
| `advancedTables.repeatables.` | The content type has a `field.repeatable()` |
`references` maps each `relation` field to the column it points at. `user` and `file` fields need no entry, because the engine knows `core_users` and `core_files`. See [Relations](/docs/content-engine/relations).
## Generated columns [#generated-columns]
You never declare these. A field with the same name throws an error.
| Column | Type | Added when |
| ------------- | ------------------------------------------------------------------------- | ------------- |
| `id` | Primary key, typed by [`idStrategy`](#ids-and-shared-tables) | Always |
| `createdAt` | `timestamp`, defaults to `now()` | Always |
| `updatedAt` | `timestamp`, defaults to `now()`, refreshed by every update | Always |
| `status` | `varchar(32)`, `draft` or `published`, defaults to `draft` | `publication` |
| `publishedAt` | `timestamp`, nullable | `publication` |
| `version` | `integer`, defaults to `1` | `editorial` |
| `hiddenAt` | `timestamp`, nullable | `visibility` |
| `hiddenBy` | `integer`, nullable, references `core_users.id` with `ON DELETE SET NULL` | `visibility` |
| `hiddenReason` | `varchar(500)`, nullable | `visibility` |
Column names are camelCase in SQL, exactly as in TypeScript. Every generated table has row-level security enabled. A field group adds one column per leaf to the main table, so the `syndication` group's `indexable` field becomes `syndicationIndexable`. Column types per field are listed in [Fields](/docs/content-engine/fields).
### Translations table [#translations-table]
With `localization`, `{tableName}_translations` holds the localized fields:
| Column | Notes |
| ------------------------ | ------------------------------------------------------------------------------------------------------- |
| `itemId` | References the main table, with the same type as its `id`. Deleting the record deletes its translations |
| `languageId` | References `core_languages.id`. A language with content cannot be deleted |
| `version` | Per-language version, always present |
| `createdAt`, `updatedAt` | Same as the main table |
| `status`, `publishedAt` | With `publication`. Each language is published on its own |
The primary key is `(itemId, languageId)`, so a record has at most one translation per language.
### Junction and child tables [#junction-and-child-tables]
Field names become snake_case in table names, so `relatedExplainers` on `newsroom_explainers` becomes `newsroom_explainers_related_explainers`.
- A **to-many field** gets `{tableName}_{field}` with `itemId`, `relatedItemId`, `position` and `createdAt`. The primary key is `(itemId, relatedItemId)`, so a record links to each target once.
- A **repeatable field** gets `{tableName}_{field}` with `id`, `itemId`, `position`, `createdAt`, `updatedAt` and one column per subfield.
Deleting a record deletes its junction and repeatable rows. Both kinds keep `position` unique per record. That column holds the order an editor picks in the AdminCP.
Every column that points at a record has the type of that record's key. In a junction table, `itemId` follows the owner's `idStrategy` and `relatedItemId` follows the target's. A repeatable's own `id` is always `serial`, while its `itemId` follows the owner. User and file references are always `integer`.
## IDs and shared tables [#ids-and-shared-tables]
The [id strategy](/docs/content-engine/id-strategy) sets the key column:
| `idStrategy` | `id` column |
| -------------------- | ----------------------------------------------------- |
| `"serial"` (default) | `serial PRIMARY KEY` |
| `"uuid"` | `uuid PRIMARY KEY DEFAULT gen_random_uuid()` |
| `"bigint"` | `bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY` |
Core tables that hold records of every content type store the id as text: `core_content_revisions`, `core_content_schedules`, `core_content_slug_history`, `core_search_index`, the [live editing](/docs/content-engine/live-editing-api#where-the-data-lives) tables `core_content_drafts`, `core_content_field_locks` and `core_content_documents`, and `core_ai_translation_sources`. Their `itemId` is a `varchar(64)` holding `contentIdKey(id)`: the digits of a serial or bigint id, or the UUID. Migration `20261011093549_content_visibility_id_strategies` converted them in place from `integer`, so existing serial keys keep their digits:
```sql title="apps/api/migrations/20261011093549_content_visibility_id_strategies/migration.sql (excerpt)"
ALTER TABLE "core_content_revisions" ALTER COLUMN "itemId" SET DATA TYPE varchar(64) USING "itemId"::varchar(64);
```
Custom SQL that joins these tables to a content table needs a cast, such as `"core_content_revisions"."itemId" = "newsroom_stories"."id"::text`.
## Generated indexes [#generated-indexes]
The engine creates these indexes without being asked:
- A unique index on every slug, and on every `field.text({ unique: true })`.
- An index on every single `relation`, `user` and `file` column, and on `hiddenBy` with `visibility`.
- Indexes on `createdAt` and `updatedAt`.
- `(status, publishedAt)` with `publication`.
- On a translations table: `(languageId, status)` with `publication` or `(languageId)` without it, plus a unique `(languageId, slug)` for each localized slug.
- On a junction table: `relatedItemId`, and a unique `(itemId, position)`. On a repeatable table: a unique `(itemId, position)`.
Generated names follow `{table}_{columns}_idx`, or `_key` for unique ones, such as `newsroom_categories_created_at_idx`. Add your own with the [`indexes`](/docs/content-engine/reference) option. An index on the same columns as a generated one replaces it instead of adding a second one:
```ts title="plugins/newsroom/src/content/story.ts (excerpt)"
indexes: [{ on: ["status", "createdAt"] }],
```
## Change a content type later [#change-a-content-type-later]
Changing a definition is a schema change like any other. Build, migrate and read the generated SQL before you commit it.
- **Adding a nullable field, or one with a `defaultValue`,** is safe on a table that already has rows.
- **Adding a required field without a default** fails on a table with rows. Add it as nullable, fill it, then make it required in a second migration.
- **Renaming a field** renames its column. Check that the generated SQL says `RENAME COLUMN`, not a drop followed by an add, or the old values are lost.
- **Turning on `localization`** moves localized fields to a new translations table. The generated SQL does not copy existing values, so add the data move to the migration yourself.
- **Turning on `visibility`** adds two nullable columns, so existing records stay visible.
- **Changing `idStrategy`** on a table with data is not something the generated SQL can do. It needs a hand-written data migration that converts the key, every column that references it and the keys in the shared tables. See [Change the strategy later](/docs/content-engine/id-strategy#change-the-strategy-later).
- **Never edit or regenerate a migration that has already been applied.** Write a new one instead.
# Duplication (/docs/content-engine/duplicate-content)
Duplication copies one record into a new draft: every field, every translation, relations in their order and repeatable rows. The blog uses it so an editor can start a new article from a similar one, or prepare a rewrite of a published article without touching the live version.
### Turn on duplication [#turn-on-duplication]
Add `duplication: true` to the definition. The blog's article content type does exactly that:
```ts title="plugins/blog/src/content/post.ts"
export const blogPostContentType = defineContentType({
id: "blog.post",
tableName: "blog_posts",
publication: true,
duplication: true, // [!code ++]
// ...
});
```
Duplication adds no column, so there is nothing to migrate, and no new permission. Duplicating needs `can_create` and `can_view`, because it creates a record by reading another. For the blog those are **Create articles** and **View articles list**.
### Duplicate an article in the AdminCP [#duplicate-an-article-in-the-admincp]
Open **AdminCP → Blog → Articles**, open the **More actions** menu of an article and choose **Duplicate**. Confirm with **Yes, duplicate it**:
The list refreshes, a toast says the article was duplicated as a draft, and the copy opens on its edit page (or in the edit dialog, for a content type whose `admin.edit.mode` is `"dialog"`). If some of the source's languages are switched off on this site, a second toast lists the ones that were left out.
Duplicating the blog's "Hello world", published in English and Polish with its categories and authors, creates a draft with:
| Language | Title | Slug |
| -------- | -------------------- | -------------------- |
| English | Hello world (Copy) | `hello-world-copy` |
| Polish | Witaj świecie (Copy) | `witaj-swiecie-copy` |
The copy has the same categories and the same authors in the same order, and each language starts its own revision history.
## What the copy contains [#what-the-copy-contains]
| Copied | Not copied |
| ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| Every declared field, including rich text, groups and blocks | Revisions, schedules and preview links |
| Repeatable rows, as new rows in the same order | Slug history and redirects |
| Relation, user and file references, in their order. Files are reused, not uploaded again | Published state and `publishedAt`: the copy is a draft |
| Every translation, each as a draft with its own first revision | Hidden state: the copy is never [hidden](/docs/content-engine/content-visibility) |
The copy gets a new id, new timestamps and `version` 1. Everything happens in one database transaction, so a failure leaves nothing behind. The source is only read, so its history gets no new revision.
### Titles and slugs [#titles-and-slugs]
When `admin.titleField` is a `field.text()`, the copy's title gets a suffix in each language, such as "Hello world (Copy)". The source title is shortened when the suffix would push it past the field's `maxLength`. The suffix is the core API message `core.content.duplicate.title_suffix`, resolved in each copied language and falling back to "(Copy)".
Turn the suffix off with `duplication: { titleSuffix: false }`. `titleSuffix: true` with a title field that is not a text field throws when the content type is defined.
Each slug is regenerated from the copy's title, so `hello-world` becomes `hello-world-copy`. A slug without a `source` gets `-copy` appended. When that slug is taken, by a live record or by another record's old URL, the engine tries `-2`, `-3` and so on, up to 20 candidates.
### Unique fields [#unique-fields]
A `field.text({ unique: true })` cannot keep the source's value. Duplicating such a record without a new value fails before anything is written, with `422` and the code `CONTENT_DUPLICATE_UNIQUE_REQUIRED`. Pass the new value as an override from the API, as shown below.
## Duplicate from the API [#duplicate-from-the-api]
The admin module of a content type with duplication has `POST /{id}/duplicate`. For the blog, the module is named after its permission module, `posts`:
```http
POST /api/@vitnode/blog/admin/content/posts/701/duplicate
Content-Type: application/json
{
"translations": {
"en": { "title": "Hello again", "friendlyUrl": "hello-again" },
"pl": { "title": "Witaj ponownie" }
}
}
```
The body is optional:
| Name | Type | Description |
| -------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `overrides` | Partial shared field values | Values the copy takes instead of the source's. A group is merged leaf by leaf. Validated like a create |
| `translations` | `{ [locale]: partial localized values }` | Localized values per copied language. A language the source has no translation in is a `400` |
A slug you pass is used as it is, without `-copy`, and a title you pass is used without the "(Copy)" suffix. In the example above, the English copy is "Hello again" at `hello-again`, and the Polish copy is "Witaj ponownie" with the slug `witaj-ponownie` generated from that title.
The response is `201` with `{ id, sourceId, row, locales, skippedLocales }`: the copy's id, the source id, the new row, the copied languages and the languages left out because they are switched off.
| Status | When |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `400` | An invalid id, override or translation |
| `403` | Missing `can_create` or `can_view` |
| `404` | The source does not exist |
| `409` | No free slug was found (`CONTENT_DUPLICATE_SLUG_CONFLICT`, with `field`, `locale` and `slug`), or an override collides with another record |
| `422` | A unique field needs an override (`CONTENT_DUPLICATE_UNIQUE_REQUIRED`, with `fields`) |
## Duplicate from your own code [#duplicate-from-your-own-code]
`service(c).duplicate(sourceId, options)` and `editorialService(c, { pluginId }).duplicate(sourceId, { actor, ...options })` take the same `overrides` and `translations`, plus `tx`. Both exist only when duplication is on, and both return `null` when the source does not exist.
The services do not emit events or index the copy. Run `contentDuplicateEffects` from `@vitnode/core/content/server` after the transaction commits, as the generated route does:
```ts
import { contentDuplicateEffects, resolveContentActor } from "@vitnode/core/content/server";
const { editorialService } = postContent;
if (!editorialService) throw new Error("Articles have no editorial features.");
const pluginId = manifest.id;
const actor = resolveContentActor(c);
const outcome = await editorialService(c, { pluginId }).duplicate(sourceId, {
actor,
});
if (outcome) {
await contentDuplicateEffects(
c,
postContent,
{ kind: "editorial", outcome },
{ actorUserId: actor.userId, pluginId },
);
}
```
The effects emit `content.blog.post.created` with `duplicatedFromId`, one `translation_created` per copied language, and then `content.blog.post.duplicated`. They also add the copy to the search index as a private draft. See [Events](/docs/content-engine/events).
## Check the result [#check-the-result]
Duplicate "Hello world" and go back to the list. "Hello world (Copy)" is a **Draft**, and `/blog/article/hello-world-copy` answers `404` until you publish it. Open the original's **History** and you'll find no new revision. As far as the original knows, nothing happened.
# Previews (/docs/content-engine/editorial-previews)
A preview link lets a reviewer read a draft without signing in. It needs [`editorial`](/docs/content-engine/editorial) and a [public API](/docs/content-engine/public-api), and a page that knows how to load the draft. The examples use `newsroom.story` from the newsroom plugin.
## Turn on previews [#turn-on-previews]
Add `preview` to the `editorial` block. `expiresInMinutes` defaults to 15 and accepts 1 to 1440:
```ts title="plugins/newsroom/src/content/story.ts (excerpt)"
editorial: {
revisions: { retention: 20 },
preview: { expiresInMinutes: 30 }, // [!code ++]
scheduling: true,
},
```
`preview` changes no columns. Leaving out `publicApi` is a type error, and the definition throws when it loads.
## Create and open a link [#create-and-open-a-link]
In the AdminCP, open **More actions** and choose **Preview**. Creating a link needs `can_view`.
The link is HMAC-signed, expires after `expiresInMinutes` and cannot be revoked early, so treat it like a password. It is pinned to the last saved version, so it shows what **Save** committed, not unsaved [live editing](/docs/content-engine/live-editing) drafts. Want those too? Use the [live preview](#live-preview).
The link points to the first of these that exists:
1. `preview.pathTemplate`, such as `/preview/stories/{token}`, with exactly one `{token}`.
2. The record's own page with `?preview=`, when the type has [delivery](/docs/content-engine/public-pages).
3. The public API route `GET /api/newsroom/content/stories/preview/{token}`.
Every page still has to load the draft from that API route. A page built from [Content page](/docs/content-engine/public-pages) does not read `?preview=` on its own, so a story's preview link opens a 404 until you check for it in your loader:
```ts title="Read a preview in a page loader"
const preview = await fetcher({
plugin: "newsroom",
method: "get",
module: "content/stories",
path: "/preview/{token}",
args: { params: { token: encodeURIComponent(token) } },
});
```
The route returns the record's public fields, and the same `404` for a forged, expired or unknown token. It sends `Cache-Control: private, no-store` and `X-Robots-Tag: noindex, nofollow`, so the draft stays out of caches and search results.
VitNode builds links from `VITNODE_WEB_URL` and `VITNODE_API_URL`. When either is not an absolute URL, the API logs a warning at startup and the **Preview** button answers `503`.
## Live preview [#live-preview]
The live preview puts the real page next to the form, and it updates as you type, before anything is saved. In the blog's article editor, click **Live preview** (the eye icon) in the header, and the page slides in from the right:
- The screen size buttons switch between **Fit to panel**, **Mobile**, **Tablet** and **Desktop**. Fixed sizes shrink to fit the panel, so a desktop page still fits on a laptop.
- **Open in a new tab** pops the preview out, and that tab keeps following your edits.
- On phones, the preview takes the whole screen. Click the eye again to get back to the form.
### Add it to your editor [#add-it-to-your-editor]
`ContentLivePreview` comes from `@vitnode/core/content/admin-form`. Render it in your [custom form layout](/docs/content-engine/admincp):
```tsx title="A custom form layout (excerpt)"
import type { ContentFormLayoutProps } from "@vitnode/core/lib/plugin";
import { Button } from "@vitnode/core/components/ui/button";
import { ContentLivePreview } from "@vitnode/core/content/admin-form";
import { EyeIcon } from "lucide-react";
import React from "react";
export const StoryFormLayout = ({
contentTypeId,
itemId,
}: ContentFormLayoutProps) => {
const [open, setOpen] = React.useState(false);
return (
<>
{open && itemId !== undefined ? (
{
setOpen(false);
}}
/>
) : null}
>
);
};
```
`ContentLivePreview` creates a preview link for `locale` (falling back to the default language when that translation was never saved), opens it in an iframe and sends the unsaved form values to it with `postMessage`. It renews the link before it expires, so a long writing session doesn't end in a 404.
### Follow the edits in your page [#follow-the-edits-in-your-page]
The page behind the link reads the values with `useContentLivePreview` from `@vitnode/core/tanstack/content` and lays them over the record it loaded:
```tsx title="The preview page (excerpt)"
import type { MultiLangValue } from "@vitnode/core/lib/helpers/multi-lang";
import { getLangValue } from "@vitnode/core/lib/helpers/multi-lang";
import { useContentLivePreview } from "@vitnode/core/tanstack/content";
const StoryTitle = ({ saved }: { saved: string }) => {
const live = useContentLivePreview();
const values = live?.values as { title?: MultiLangValue } | undefined;
return
;
};
```
The values come exactly as the AdminCP form holds them: a localized field is `{ languageCode, value }[]`, and relations, users and files are ids. For users and files, `live.references.people` and `live.references.files` hold the full objects, including an author picked or a cover uploaded a second ago, so look each id up there first, then in the record the page loaded. Relations stay ids, so map those to the objects the page already loaded. The hook returns `null` until the editor sends something, which is all it ever returns when someone opens the link on its own. It only reads messages from the same origin, sent by the window that embeds or opened the page.
The blog does this in `plugins/blog/src/pages/post-preview-page.tsx`, with `pathTemplate: "/blog/preview/{token}"`.
# Scheduling (/docs/content-engine/editorial-scheduling)
Scheduling publishes or unpublishes a record at a chosen time. It needs [`editorial`](/docs/content-engine/editorial) and [drafts & publishing](/docs/content-engine/publication), and a running cron job. The examples use `newsroom.story` from the newsroom plugin.
## Turn on scheduling [#turn-on-scheduling]
Add `scheduling` to the `editorial` block:
```ts title="plugins/newsroom/src/content/story.ts (excerpt)"
editorial: {
revisions: { retention: 20 },
preview: { expiresInMinutes: 30 },
scheduling: true, // [!code ++]
},
```
`scheduling` changes no columns. Leaving out `publication` is a type error, and the definition throws when it loads.
## Book a schedule [#book-a-schedule]
Open **More actions**, choose **Schedule**, pick **Publish** or **Unpublish** and a time, then press **Schedule it**. Booking or cancelling a schedule needs `can_publish`.
A schedule is a queued task, and the `process-queue` [cron job](/docs/dev/cron) drains the queue once a minute. If nothing triggers your cron endpoint, schedules still save but never fire. When the install has no cron adapter at all, the dialog says so with a **No scheduler is running** warning. When a schedule fires, it publishes whatever the record says at that moment, not what it said when you booked it.
A few rules keep schedules sane:
- The API accepts a time up to two minutes in the past. Anything older fails with `CONTENT_SCHEDULE_IN_PAST`.
- An unpublish cannot come before a pending publish (`CONTENT_SCHEDULE_ORDER`).
- Booking emits `content.newsroom.story.scheduled` and cancelling emits `schedule_cancelled`. When the time comes, the usual `published` or `unpublished` event carries the `scheduleId`.
- A scheduled publish of a [hidden](/docs/content-engine/content-visibility) record leaves it hidden, so it stays off the public site until someone unhides it.
If a separate front end caches pages, [Notify a separate front end](/docs/content-engine/caching#notify-a-separate-front-end) tells it about the change.
# Revisions (/docs/content-engine/editorial)
The `editorial` block keeps a history of every save that staff can restore, and stops two people from overwriting each other. It is also what [previews](/docs/content-engine/editorial-previews), [scheduling](/docs/content-engine/editorial-scheduling) and [live editing](/docs/content-engine/live-editing) build on. The examples use `newsroom.story` from the newsroom plugin.
## Turn on revisions [#turn-on-revisions]
Add `editorial` to the definition. `true` keeps the newest 50 revisions per record. Set `revisions.retention` for another number, up to 500:
```ts title="plugins/newsroom/src/content/story.ts (excerpt)"
export const storyContentType = defineContentType({
id: "newsroom.story",
// ...
// [!code ++:4]
editorial: {
revisions: { retention: 20 },
// ...
},
});
```
Then migrate from the workspace root:
```bash tab="bun"
bun run db:migrate
```
```bash tab="pnpm"
pnpm db:migrate
```
```bash tab="npm"
npm run db:migrate
```
The migration adds a `version` column. Revisions, schedules, drafts and locks live in shared core tables, so nothing else lands in your schema. Editorial also adds a `can_restore` staff permission. Label it with the `newsroom:story:can_restore` key in your plugin's locale file. Every option and default is in the [content type reference](/docs/content-engine/reference#editorial).
## Revisions [#revisions]
Every create, update, publish, unpublish and restore stores a snapshot in `core_content_revisions`, and so does every hide and unhide with [`visibility`](/docs/content-engine/content-visibility). `revisions.retention` keeps the newest snapshots per record, 50 by default and at most 500.
To see them, open the row's **More actions** menu in the AdminCP list and choose **History**. Each version shows who saved it and when, and **Show changes** lists the fields it changed:
**Restore** puts that version's field values back as a new version, so nothing in between is lost. The publication status and the [hidden](/docs/content-engine/content-visibility) state stay as they are. It needs `can_restore` and emits `content.newsroom.story.restored`. Anyone with the record open in [live editing](/docs/content-engine/live-editing) gets a notice and a reloaded form.
## Safe concurrent edits [#safe-concurrent-edits]
Each editorial write raises the record's `version` by one and succeeds only when the version still matches the one the editor loaded. If someone saved in between, the second save fails instead of quietly replacing their work:
```json title="PUT /api/newsroom/admin/content/story/2 → 409"
{
"code": "CONTENT_VERSION_CONFLICT",
"contentTypeId": "newsroom.story",
"itemId": 2,
"expectedVersion": 2,
"currentVersion": 3
}
```
The AdminCP sends the version for you. Your own calls to the edit routes must send it too: `PUT /{id}` takes `{ "expectedVersion": 3, "values": { "title": "…" } }` and `DELETE /{id}` takes `{ "expectedVersion": 3 }`. In server code, `storyContent.editorialService` does the same check, as [Save like the AdminCP](/docs/content-engine/services#save-like-the-admincp) shows. A translation has its own version and fails with `CONTENT_TRANSLATION_VERSION_CONFLICT`.
# Events (/docs/content-engine/events)
Each content type emits events named `content..` after a change, such as `content.newsroom.story.published`. Subscribe to them to send a newsletter, sync an external index or purge a CDN, without touching the code that made the change.
Events come from the generated routes, scheduled publishing and [`contentEditorialEffects`](/docs/content-engine/services#save-like-the-admincp). The plain `service(c)` emits nothing. A save that changes nothing emits nothing either.
## Event reference [#event-reference]
Which events exist depends on what the definition enables. `newsroom.category` declares only fields and emits three. `newsroom.story` has publication, editorial with scheduling and delivery, and emits ten.
| Action | Payload | Needs |
| --------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------ |
| `created` | `{ contentId, duplicatedFromId? }` | always |
| `updated` | `{ contentId, changedFields }` | always |
| `deleted` | `{ contentId }` | always |
| `published` | `{ contentId, publishedAt, scheduledBy?, scheduleId? }` | `publication` |
| `unpublished` | `{ contentId, scheduledBy?, scheduleId? }` | `publication` |
| `restored` | `{ contentId, changedFields, version, revisionId, restoredFromRevisionId }` | `editorial` |
| `scheduled` | `{ contentId, action, actorUserId, scheduledFor, scheduleId }` | `editorial.scheduling` |
| `schedule_cancelled` | `{ contentId, action, actorUserId, scheduleId }` | `editorial.scheduling` |
| `translation_created` | `{ contentId, locale, languageId, version, revisionId? }` | `localization` |
| `translation_updated` | `{ contentId, locale, languageId, version, changedFields, revisionId? }` | `localization` |
| `translation_deleted` | `{ contentId, locale, languageId, version, revisionId? }` | `localization` |
| `translation_published` | `{ contentId, locale, languageId, version, publishedAt, revisionId? }` | `localization` + `publication` |
| `translation_unpublished` | `{ contentId, locale, languageId, version, revisionId? }` | `localization` + `publication` |
| `translation_restored` | `{ contentId, locale, languageId, version, changedFields, revisionId, restoredFromRevisionId }` | `localization` + `editorial` |
| `delivery_slug_changed` | `{ contentId, slug, previousSlug, previousPath, canonicalPath, locale }` | `delivery` |
| `delivery_redirect_created` | `{ contentId, previousSlug, previousPath, canonicalPath, locale }` | `delivery` |
| `duplicated` | `{ actorUserId, contentId, contentTypeId, sourceId }` | `duplication` |
| `hidden` | `{ actorUserId, contentId, hiddenAt }` | `visibility` |
| `unhidden` | `{ actorUserId, contentId }` | `visibility` |
A few payload details that change what a listener does:
- `contentId` has the type of the content type's [id strategy](/docs/content-engine/id-strategy): a `number` for `serial`, a `string` for `uuid` and `bigint`. A bigint id arrives as its exact decimal string.
- A [duplicate](/docs/content-engine/duplicate-content) emits the copy's `created` with `duplicatedFromId`, one `translation_created` per copied language, then `duplicated`. `duplicatedFromId` is absent on an ordinary create.
- `hidden` and `unhidden` never replace `published` or `unpublished`, because [hiding](/docs/content-engine/content-visibility) does not change the status.
- `changedFields` lists only the fields whose value actually moved, typed as the content type's own field names. On translation events it names localized fields only.
- `restored` replaces `updated` for a rollback, so a listener that cares about field changes should handle both.
- `publishedAt` is when the record first went live. It is never rewritten, and it can be missing, so guard for `undefined`.
- `scheduledBy` and `scheduleId` are set only when a schedule fired the change. `actorUserId` on `scheduled` is the same person as `scheduledBy` later.
- The delivery events arrive alongside `updated`, `restored` or a publication event, never instead of them. `locale` is `null` for a shared slug.
[Container collections](/docs/content-engine/containers) emit their own four events, `content.container.created`, `updated`, `moved` and `deleted`, listed in [Container hierarchy](/docs/content-engine/container-hierarchy#events).
A record waiting for [approval](/docs/content-engine/approvals) emits its `published` or `updated` only when a moderator approves it, once. The submission itself emits `content.approval.submitted`, `approved` and `rejected`, listed in [Built-in events](/docs/dev/events/built-in-events#content-approval-events).
The listener also receives an envelope with the actor, the time and `pluginId`. `pluginId` is always the plugin that owns the content type, even when a core queue task ran the change. Field-by-field descriptions are in [Built-in events](/docs/dev/events/built-in-events#content-engine-events).
## Subscribe to an event [#subscribe-to-an-event]
### Register the event types [#register-the-event-types]
Add the content type to the global event map once per plugin. The listener's event name and payload are then type-checked, and an event the definition does not enable, such as `content.newsroom.category.published`, does not compile.
```ts title="plugins/newsroom/src/api/lib/events.ts"
import type { ContentEventsFor } from "@vitnode/core/content";
import type { categoryContentType } from "@/content/category";
import type { storyContentType } from "@/content/story";
declare module "@vitnode/core/api/models/events" {
interface VitNodeEvents
extends
ContentEventsFor,
ContentEventsFor {}
}
```
The newsroom plugin imports this file from `config.api.ts` with `import "@/api/lib/events";`, so the declaration travels with the API build.
### Write the listener [#write-the-listener]
`contentEventName(id, action)` builds the name from the definition, so a renamed content type cannot leave a stale string behind:
```ts title="plugins/newsroom/src/api/lib/listeners.ts"
import { buildEventListener } from "@vitnode/core/api/lib/events";
import { contentEventName } from "@vitnode/core/content";
import { storyContentType } from "@/content/story";
export const announceStoryListener = buildEventListener({
event: contentEventName(storyContentType.id, "published"),
name: "announce-published-story",
description: "Logs every story that goes live",
handler: async (c, payload) => {
await c.get("log").debug(`Story ${payload.contentId} was published`);
},
});
```
### Add it to a top-level module [#add-it-to-a-top-level-module]
VitNode collects listeners only from the `events` array of a module passed directly to `buildApiPlugin`. A listener on a nested module never runs: `buildApiPlugin` throws in development to say so, and [`vitnode doctor`](/docs/dev/cli/doctor) reports it. Production ignores it.
```ts title="plugins/newsroom/src/api/modules/admin/admin.module.ts (excerpt)"
export const adminModule = buildModule({
name: "admin",
routes: [],
modules: [
buildContentAdminModule({
containers: [deskContainers],
contentTypes: [
articleContent,
categoryContent,
commentContent,
storyContent,
explainerContent,
bulletinContent,
tagContent,
eventContent,
pageContent,
letterContent,
],
}),
],
events: [announceStoryListener], // [!code ++]
});
```
The blog plugin does the same with its `blogLegacyEventListeners`, which turn `content.blog.post.created` into the older `blog.post.created` event.
## Check the result [#check-the-result]
Save the file, publish a story in **AdminCP → Newsroom → Stories** and look for the debug line in the API terminal. A failing listener does not undo the change. The write has already committed, and the engine logs the failure.
Events from a scheduled publish run in a queue task that retries on failure, so the same `published` event can arrive twice. Make work that must happen once idempotent, for example keyed on `scheduleId`. See [A scheduled event may arrive twice](/docs/dev/events/built-in-events#a-scheduled-event-may-arrive-twice).
# Fields (/docs/content-engine/fields)
A field is one property of a content type, such as a title or a view count. You build each one with a helper from `field`, exported by `@vitnode/core/content`. The helper decides three things at once: the Postgres column, the validation of every write and the control in the AdminCP form.
```ts title="plugins/newsroom/src/content/story.ts (excerpt)"
import { defineContentType, field } from "@vitnode/core/content";
export const storyContentType = defineContentType({
id: "newsroom.story",
tableName: "newsroom_stories",
fields: {
title: field.text({ required: true, minLength: 3, maxLength: 200 }),
slug: field.slug({ source: "title" }),
views: field.number({ integer: true, min: 0, defaultValue: 0 }),
featured: field.boolean({ defaultValue: false }),
author: field.user(),
},
});
```
The newsroom plugin's story form shows most controls. The first half holds the plain values:
The second half holds the references: a user picker, two file dropzones and a relation picker.
## Field helpers [#field-helpers]
| Helper | Postgres column | AdminCP control | Can be `localized` |
| -------------------- | -------------------------------------------------- | ---------------------------------------- | ------------------ |
| `field.text()` | `varchar(maxLength)`, 255 by default | Text input | Yes |
| `field.textarea()` | `text` | Textarea | Yes |
| `field.richText()` | `jsonb` | Rich text editor | Yes |
| `field.number()` | `integer` or `double precision` | Number input with steppers | No |
| `field.boolean()` | `boolean` | Switch | No |
| `field.enum()` | `varchar(length)`, 64 by default | Select or radio buttons | No |
| `field.dateTime()` | `timestamp` | Date and time picker | No |
| `field.slug()` | `varchar(maxLength)`, 160 by default, unique | Text input | Yes |
| `field.user()` | `integer` referencing `core_users.id` | User picker | No |
| `field.file()` | `integer` referencing `core_files.id` | File dropzone | No |
| `field.relation()` | The target's key type, referencing its table | Search picker | No |
| `field.container()` | `integer` referencing `core_content_containers.id` | Container tree picker | No |
| `field.group()` | One column per leaf | A fieldset with the leaf controls | Yes, as a whole |
| `field.repeatable()` | A child table | A list of rows you can add, move, remove | No |
| `field.blocks()` | `jsonb`, `NOT NULL DEFAULT '[]'` | Not in the form; edited as widgets | Yes |
`user`, `file` and `relation` with `multiple: true` store their values in a junction table instead of a column. Localized fields live in the translation table. See [Translations](/docs/content-engine/localization).
## Shared options [#shared-options]
Every helper except `slug`, `repeatable` and `blocks` accepts these:
| Name | Type | Required | Default | Description |
| ------------- | --------- | -------- | ------- | ---------------------------------------------------------- |
| `required` | `boolean` | No | `false` | A create request must include the field |
| `nullable` | `boolean` | No | `false` | The column accepts `NULL`, and so does validation |
| `description` | `string` | No | | Text or an i18n key shown under the control in the AdminCP |
A field that is neither required nor nullable needs a fallback, or `defineContentType` throws `Field "x" is neither required nor nullable, so it needs a default value`. A `defaultValue`, `defaultNow: true` on a date and `source` on a slug all count as a fallback. On update every field is optional.
`required: true` on a text field still accepts an empty string. Add `minLength: 1` when you need actual text.
## Text and textarea [#text-and-textarea]
```ts
code: field.text({ required: true, maxLength: 100, unique: true }),
excerpt: field.textarea({ maxLength: 500, nullable: true }),
```
| Name | Type | Required | Default | Description |
| -------------- | --------- | -------- | -------------------- | ------------------------------------------------------------------------ |
| `minLength` | `number` | No | | Shortest accepted value, in characters |
| `maxLength` | `number` | No | 255 column on `text` | Longest accepted value. On `text` it is also the `varchar` length |
| `defaultValue` | `string` | No | | Written when a create leaves the field out. Becomes the column `DEFAULT` |
| `unique` | `boolean` | No | `false` | `text` only. Adds a unique index. Has no effect on a localized field |
| `localized` | `boolean` | No | `false` | One value per language |
| `ai` | object | No | | Adds an AI suggestion button, see [AI suggestions](#ai-suggestions) |
Set `maxLength` on every `text` field. Without it, validation accepts any length, and Postgres rejects anything over 255 characters with a database error instead of a validation message. A `defaultValue` must satisfy the field's own `minLength` and `maxLength`.
## Rich text [#rich-text]
```ts
content: field.richText({ localized: true, required: true }),
```
| Name | Type | Required | Default | Description |
| ----------- | --------- | -------- | ------- | ------------------------------------------------------- |
| `maxBytes` | `number` | No | 1 MB | Largest document, measured as UTF-8 JSON. At most 16 MB |
| `localized` | `boolean` | No | `false` | One document per language |
| `uploads` | `boolean` | No | `false` | The AdminCP editor accepts images, see [Editor images](/docs/ui/editor-images) |
The value is a ProseMirror JSON document. A rich text field has no `defaultValue`, so set `required` or `nullable`. With `required: true` a document without any text or media is refused. Documents nested deeper than 64 levels are refused too. [Rich text](/docs/content-engine/rich-text) covers rendering and the plain text and HTML helpers.
## Number [#number]
```ts
views: field.number({ integer: true, min: 0, defaultValue: 0 }),
```
| Name | Type | Required | Default | Description |
| -------------- | --------- | -------- | ------- | ------------------------------------------------------------------------- |
| `integer` | `boolean` | Yes | | `true` makes an `integer` column, `false` a `double precision` one |
| `min`, `max` | `number` | No | | Accepted range. With `integer: true` a whole number must fit between them |
| `defaultValue` | `number` | No | | Must sit inside the range, and be whole when `integer: true` |
## Boolean [#boolean]
```ts
featured: field.boolean({ defaultValue: false }),
```
The only option besides the shared ones is `defaultValue`. A nullable boolean, such as `noIndex: field.boolean({ nullable: true })`, can hold `true`, `false` or `null`.
## Enum [#enum]
```ts
difficulty: field.enum({ values: ["easy", "medium", "hard"], defaultValue: "easy", display: "radio" }),
```
| Name | Type | Required | Default | Description |
| -------------- | ----------------------- | -------- | ---------- | -------------------------------------- |
| `values` | `string[]` | Yes | | Non-empty, without duplicates |
| `defaultValue` | one of `values` | No | | |
| `display` | `"select"` \| `"radio"` | No | `"select"` | AdminCP control |
| `length` | `number` | No | `64` | `varchar` length. Every value must fit |
The column is a plain `varchar`, not a Postgres enum, so adding a value later needs no type migration. The AdminCP translates each value from `{pluginId}.content.{entity}.enums.{field}.{value}` when that key exists.
## Date and time [#date-and-time]
```ts
eventDate: field.dateTime({ defaultNow: true }),
```
| Name | Type | Required | Default | Description |
| ------------ | --------- | -------- | ------- | ------------------------------------------------ |
| `defaultNow` | `boolean` | No | `false` | Fills the column with the current time on insert |
There is no `defaultValue`. Send dates as ISO 8601 strings.
## Slug [#slug]
```ts
slug: field.slug({ source: "title" }),
```
| Name | Type | Required | Default | Description |
| ------------- | -------------------- | -------- | ------- | ---------------------------------------------------------- |
| `source` | name of a text field | No | | Fills the slug from that field when a create sends no slug |
| `generated` | `boolean` | No | `false` | Mints a random token when a create sends no slug. Not with `source` |
| `maxLength` | `number` | No | `160` | `varchar` length and the point where long slugs are cut |
| `localized` | `boolean` | No | `false` | One slug per language |
| `description` | `string` | No | | Shown under the input |
A slug has no `required` or `nullable` option. It is required when there is no `source`, and it is never empty. Every value is normalized, so `"Weekend Pancakes!"` becomes `weekend-pancakes`. Slugs are unique across the table, or within each language when localized. The slug is derived only on create, so renaming the title later keeps the old URL. `source` must name a `field.text()`, and a localized slug needs a localized source.
For records without a natural title, such as forum comments, use `field.slug({ generated: true })`. The server mints a random token of lowercase letters and digits, 10 characters or `maxLength` if shorter, such as `k3v9q2m7xa`. A generated slug cannot be `localized` or have a `source`, and it is never [publicly writable](/docs/content-engine/public-write-api#writable-fields). See [Comments](/docs/content-engine/threads).
## User [#user]
```ts
author: field.user(),
authorId: field.user({ multiple: true, ordered: true, min: 1 }),
```
| Name | Type | Required | Default | Description |
| ---------- | ------------------------------------------- | -------- | --------- | ------------------------------------------ |
| `multiple` | `boolean` | No | `false` | Several people, stored in a junction table |
| `ordered` | `boolean` | No | `false` | Keeps the order editors arrange |
| `min` | `number` | No | | Fewest people. Needs `multiple` |
| `onDelete` | `"cascade"` \| `"restrict"` \| `"set null"` | No | see below | What deleting the user does |
A single user field is nullable unless you set `required: true`. `onDelete` defaults to `"set null"` for a nullable single user, `"restrict"` for a required one and `"cascade"` for `multiple`. User fields cannot be listed in `publicApi.fields`. To publish an author's name and avatar, name a single, shared user field in [`publicApi.people`](/docs/content-engine/reference#publicapi) instead.
## File [#file]
```ts
animation: field.file({
maxBytes: 10 * 1024 * 1024,
allowedExtensions: [".gif"],
allowedMimeTypes: ["image/gif"],
}),
gallery: field.file({ multiple: true, min: 1, max: 8, maxBytes: 5 * 1024 * 1024 }),
```
| Name | Type | Required | Default | Description |
| ------------------- | ---------- | -------- | ------------------ | ------------------------------------------ |
| `maxBytes` | `number` | Yes | | Largest accepted file, in bytes |
| `allowedExtensions` | `string[]` | No | any | Lowercased, with a leading dot added |
| `allowedMimeTypes` | `string[]` | No | any | Lowercased |
| `multiple` | `boolean` | No | `false` | Several files in a junction table |
| `min` | `number` | No | | Fewest files, at least 1. Needs `multiple` |
| `max` | `number` | No | `20` | Most files, up to 200. Needs `multiple` |
| `ordered` | `boolean` | No | same as `multiple` | Keeps the order editors arrange |
A single file field is nullable unless you set `required: true`, and it cannot have a default or be localized. Translate a caption or alt text in a separate localized text field instead. Uploads go through the [storage](/docs/dev/storage) adapter and land in `core_files`. A file in use cannot be deleted, because the reference is `ON DELETE RESTRICT`.
The public API returns a file as `{ id, name, url, mimeType, size, width, height }`, never as a raw id. A write may only point at a file uploaded for this content type, uploaded by the signed-in user, or already on the record. The API refuses anything else with `CONTENT_FILE_NOT_FOUND`.
## Relation [#relation]
```ts
category: field.relation({ required: true, onDelete: "restrict", target: () => categoryContentType }),
```
| Name | Type | Required | Default | Description |
| ---------- | ------------------------------------------- | ------------------ | ------------ | ---------------------------------------------------------------------------- |
| `target` | `() => ContentTypeDefinition` | Yes, unless `self` | | The linked content type |
| `self` | `true` | No | `false` | Links to the same content type. Do not combine with `target` |
| `multiple` | `boolean` | No | `false` | Uses a junction table, up to 500 targets per record |
| `ordered` | `boolean` | No | `false` | Keeps the editor's order. Needs `multiple` |
| `min` | `number` | No | | Fewest targets, 1 to 500. Needs `multiple` |
| `onDelete` | `"restrict"` \| `"cascade"` \| `"set null"` | No | `"restrict"` | What deleting the target does. `"set null"` needs a nullable single relation |
| `container` | `boolean` | No | `false` | The record lives in the target record's [container](#container). Required, to-one, never `self` |
A single relation must be `required` or `nullable`. A to-many relation can be neither. A to-one `self: true` relation, such as the reply a reply answers, must be `nullable`, because the first record has nothing to point at.
`container: true` files the record in the container of the record it points at, such as a comment in its topic's forum. The server always reads that container from the related row, so a client cannot claim another one, and [publishing policies](/docs/content-engine/container-policies) and container-scoped moderators apply as if the record had its own `field.container()`. A content type takes its container from one field only: one `field.container()` or one `container: true` relation. The target must have a `field.container()`, or the API stops at boot with ``Field "x" is `container: true`, but its target ... is not filed in a container.`` The column has the type of the target's key: `integer`, `uuid` or `bigint`, depending on its [`idStrategy`](/docs/content-engine/id-strategy). [Relations](/docs/content-engine/relations) shows the model wiring, and [Advanced fields](/docs/content-engine/relations-advanced) the junction tables.
## Container [#container]
```ts
desk: field.container({ definition: deskContainers, required: true }),
```
| Name | Type | Required | Default | Description |
| ------------- | --------------------------------- | -------- | ------- | ------------------------------------------------------------------ |
| `definition` | `defineContentContainer()` result | Yes | | The collection the record's container comes from |
| `required` | `boolean` | No | `false` | Every record needs a container. Without it, a record may have none |
| `description` | `string` | No | | Text or an i18n key shown under the picker in the AdminCP |
`field.container()` files a record into one container of a [container collection](/docs/content-engine/containers), such as a letter into a newsroom desk. `nullable` is always the opposite of `required`, so there is no `nullable` option, no default and no `localized`. A content type can have at most one container field, and you must register its collection with `buildContentAdminModule({ containers })`.
The column is an `ON DELETE RESTRICT` foreign key with an index on the field (plus `publishedAt` when `publication` is on), so a container that still holds records cannot be deleted. Every write checks that the id belongs to the field's collection and answers `400` with `CONTAINER_NOT_FOUND` or `CONTAINER_DEFINITION_MISMATCH` otherwise.
The public API returns the container as its id. In `publicApi.filterableFields`, it filters a list with `?desk=4`, and `includeDescendants=true` widens that to the whole subtree. In `publicWrite`, it may be listed in `create.fields` but not in `update.fields`. [Container pages](/docs/content-engine/container-frontend) shows both.
## Group [#group]
```ts
syndication: field.group({
fields: {
noIndex: field.boolean({ defaultValue: false }),
priority: field.number({ integer: true, min: 0, max: 10, defaultValue: 5 }),
},
}),
```
| Name | Type | Required | Default | Description |
| ----------- | --------------------- | -------- | ------- | -------------------------------------------------------------------- |
| `fields` | object of leaf fields | Yes | | `text`, `textarea`, `number`, `boolean`, `enum` or `dateTime` leaves |
| `localized` | `boolean` | No | `false` | Moves every leaf to the translation table together |
Each leaf becomes a column named ``, such as `syndicationPriority`. Leaves cannot set `localized` themselves. An optional group needs leaves that are nullable or have a default. A nullable group needs nullable leaves.
## Repeatable [#repeatable]
```ts
faq: field.repeatable({
max: 20,
fields: {
question: field.text({ required: true, minLength: 3, maxLength: 200 }),
answer: field.textarea({ required: true }),
},
}),
```
| Name | Type | Required | Default | Description |
| ------------- | --------------------- | -------- | ------- | -------------------------- |
| `fields` | object of leaf fields | Yes | | Same leaf kinds as a group |
| `min` | `number` | No | `0` | Fewest rows |
| `max` | `number` | No | `100` | Most rows, up to 1000 |
| `description` | `string` | No | | Shown in the AdminCP form |
Rows live in a child table. A repeatable is always shared between languages.
## Blocks [#blocks]
```ts
content: field.blocks({ allowed: ["core:*", "newsroom:callout", "newsroom:features"], max: 50 }),
```
| Name | Type | Required | Default | Description |
| ------------- | ------------------- | -------- | ------- | ---------------------------------------------- |
| `allowed` | `"*"` or `string[]` | No | `"*"` | Which blocks may be placed, such as `"core:*"` |
| `min` | `number` | No | | Fewest block instances |
| `max` | `number` | No | `200` | Most block instances, up to 1000 |
| `localized` | `boolean` | No | `false` | Each language gets its own blocks |
| `description` | `string` | No | | |
`field.widgets()` is the same helper under another name. A blocks field is never required or nullable. No blocks means an empty list. It does not appear in the AdminCP form. Editors place widgets on the page itself, as described in [The blocks() field](/docs/dev/widgets/blocks-field).
## AI suggestions [#ai-suggestions]
`text` and `textarea` fields accept an `ai` option. The form then shows an **AI** button next to the label, like the excerpt in the screenshot above.
```ts
excerpt: field.textarea({
ai: {
action: "newsroom:story.excerpt",
mode: "suggestion",
sourceFields: ["title", "code"],
},
maxLength: 500,
nullable: true,
}),
```
| Name | Type | Required | Default | Description |
| -------------- | ------------------------- | -------- | ------- | ---------------------------------------------------------------------- |
| `action` | `":"` | Yes | | A registered AI action |
| `mode` | `"suggestion"` | Yes | | The only supported mode. The editor reviews the text before it is used |
| `sourceFields` | `string[]` | Yes | | Other fields of this content type sent to the action as input |
[Field suggestions](/docs/dev/ai/fields-and-editor) shows how to write the action.
## Searching and sorting [#searching-and-sorting]
Fields have no `searchable` or `sortable` option. Each surface picks its own fields: `admin.list.searchableFields` and `orderableFields` for the AdminCP list, `publicApi.searchableFields`, `orderableFields` and `filterableFields` for the public API, and `search.contentFields` for site search. The [content type reference](/docs/content-engine/reference) lists which field kinds each one accepts.
# Generate a content type (/docs/content-engine/generate)
`vitnode g resource --kind content` writes the files that [First content type](/docs/content-engine/create-a-content-type) builds by hand: the definition, the model and its table export, the staff API mount, the AdminCP sidebar entry and screen, and the labels. The Content Engine then generates the CRUD routes and permissions, as it does for a hand-written content type. The generator never writes or applies a migration.
The result is **administrative only**: staff create and edit records in the AdminCP. It has no public API, member writes, drafts or ownership rules, because each of those changes who can read or write the records. Turn them on in the definition once you decide, following the linked guides.
## Before you begin [#before-you-begin]
- A plugin made with [Create plugin](/docs/dev/plugins/create), with a terminal in its folder (here `plugins/site-notes`).
- A database, to apply the migration at the end.
### Preview the content type [#preview-the-content-type]
In the plugin folder, name the resource and list its fields as `name:type`, with `text`, `richText`, `boolean`, `int` or `number`. A `?` after a name makes the field optional. The first required `text` field becomes the title, so the list needs one:
```bash
pnpm vitnode g resource articles --kind content --fields "title:text,body:richText,featured?:boolean" --singular Article --dry-run
```
```txt
would create src/content/articles.ts content type sitenotes.articles
would create src/database/articles.ts model and table site_notes_articles
would create src/api/modules/admin/admin.module.ts module "admin"; mount articlesContent in the admin module
would create src/admin/nav.tsx AdminCP sidebar entry
would create src/admin/content.tsx AdminCP screens, re-using the sidebar list
would update src/api/builders.ts bind the Content Engine admin builder
would update src/config.api.ts register adminModule in buildApiPlugin
would update src/locales/en.json AdminCP labels for the content type
Dry run: 5 files to create, 3 to update. Nothing was written.
```
The full diff of each file comes first; the summary above closes the output.
The names are derived, never guessed from meaning:
| Value | Derived as | Override |
| ----------------- | ----------------------------------------------------- | ---------------- |
| Content type id | Plugin name without its npm scope and dashes, a dot, the resource name | `--content-id` |
| Table | Plugin name in snake_case, `_`, the resource name | `--table` |
| Permission module | The part of the id after the dot: `articles` | - |
| AdminCP path | `/admin/content//` | - |
| Id strategy | `serial`, the Content Engine default | `--id-type uuid` or `bigint` |
| Singular label | The plural, `Articles` | `--singular` |
The generator declares no permissions. The Content Engine gives the permission module `can_view`, `can_create`, `can_edit` and `can_delete`, but only when the plugin does not declare that module in `permissionStaff`, inline or through [`defineStaffPermissions`](/docs/dev/working-with-users/staff-permission-refs). A plugin that already declares `articles` with all four is fine. If it declares only some of them, the generated staff routes would need permissions nobody can be granted, so the command stops before writing:
```txt
✖ The plugin declares the permission module "articles" without can_create, can_edit, can_delete.
The Content Engine adds can_view, can_create, can_edit, can_delete to "articles" only when the plugin does not declare it, and src/config.api.ts declares it with can_view.
The generated staff routes would require permissions nobody can be granted. Nothing was written.
Add the missing ones to permissionStaff.admin["articles"] in src/config.api.ts:
{ permission: "can_create", dependsOn: ["can_view"] },
{ permission: "can_edit", dependsOn: ["can_view"] },
{ permission: "can_delete", dependsOn: ["can_view"] },
Or remove the "articles" entry, so the Content Engine declares all four itself.
```
It also stops, with the steps to finish by hand, when it cannot read the plugin's permission declarations: `permissionStaff` has to be an object literal or `staffPermissions.config`, not a variable such as `permissionStaff: permissions`.
### Generate it [#generate-it]
Run the command without `--dry-run`. The definition it writes:
```ts title="plugins/site-notes/src/content/articles.ts"
import { defineContentType, field } from "@vitnode/core/content";
export const articlesContentType = defineContentType({
id: "sitenotes.articles",
tableName: "site_notes_articles",
fields: {
title: field.text({ maxLength: 200, required: true }),
body: field.richText({ required: true }),
featured: field.boolean({ defaultValue: false }),
},
admin: {
path: "site-notes/articles",
titleField: "title",
list: {
columns: ["title", "updatedAt"],
},
},
});
```
In an existing plugin, the generator adds to what is there. The model joins the `contentTypes` of an existing `buildContentAdminModule(...)` in the `admin` module, and the sidebar entry joins `adminNav.contentTypes`. Labels are only added, never overwritten; when `src/locales/en.json` is not plain two-space JSON, the command prints them for you to add by hand. It stops before writing, with the lines to add by hand, when `src/admin/content.tsx` builds its own `adminContent` instead of re-exporting `adminNav`.
### Build and migrate [#build-and-migrate]
Migrations are generated from the plugin's build output, so the order matters:
```bash
pnpm vitnode build # in plugins/site-notes, or keep pnpm dev running
cd ../../apps/api # the app with drizzle.config.ts; apps/web in a single-app setup
pnpm vitnode db generate # writes the migration for site_notes_articles
pnpm vitnode db migrate # applies it, after asking
```
Review the migration before you apply it. The root `pnpm db:migrate` script of a Turborepo workspace generates and applies in one go without asking, so it skips that review. See [Database commands](/docs/dev/cli/database).
## Check the result [#check-the-result]
Run `pnpm vitnode plugin validate` in the plugin: **AdminCP navigation** and **Database schema** pass. Then open **AdminCP → Site notes → Articles**, choose **Create Article**, and save one.
`pnpm vitnode inspect routes` lists the generated staff routes, such as `POST /site-notes/admin/content/articles` guarded by `admin articles.can_create`. When you edit an administrator's permissions, the four permissions appear under **Site notes → Articles**.
The guides below continue the hand-written `newsroom.article` tutorial; apply their configuration to `articlesContentType` the same way.
## Related [#related]
# Record IDs (/docs/content-engine/id-strategy)
`idStrategy` decides the type of a content type's primary key. The default, `"serial"`, is an auto-incrementing integer. `"uuid"` gives random ids that reveal nothing about how many records exist. `"bigint"` gives integers that will not run out. Pick it when you create the content type, because changing it later means a [hand-written data migration](#change-the-strategy-later), and nobody enjoys those.
The newsroom plugin keys its tags by UUID:
```ts title="plugins/newsroom/src/content/tag.ts (excerpt)"
export const tagContentType = defineContentType({
id: "newsroom.tag",
tableName: "newsroom_tags",
idStrategy: "uuid", // [!code ++]
localization: { defaultLocale: "en", fallback: "default" },
publication: true,
// visibility, duplication and editorial
fields: {
name: field.text({
localized: true,
required: true,
minLength: 1,
maxLength: 100,
}),
slug: field.slug({ localized: true, source: "name" }),
// category and relatedTags relations
},
// publicApi and admin
});
```
## Strategies [#strategies]
| Strategy | Postgres key | In JSON and URLs | In TypeScript |
| -------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------- |
| `"serial"` (default) | `serial`, up to 2,147,483,647 | A number: `42` | `number` |
| `"uuid"` | `uuid`, `DEFAULT gen_random_uuid()` | A lowercase string: `"047d2c6c-1d86-47e2-bcd3-2df9f5359541"` | `string` |
| `"bigint"` | `bigint GENERATED BY DEFAULT AS IDENTITY`, up to 9,223,372,036,854,775,807 | A decimal string: `"9007199254740994"` | `string` |
Choose by what the ids are for:
- **`serial`** suits most content. Ids are short and readable in URLs and logs. The blog's articles and categories use it.
- **`uuid`** suits content whose ids should not be guessable or countable, or records created in several places that must not collide. The newsroom plugin's `newsroom.tag` uses it.
- **`bigint`** suits tables that may outgrow two billion rows, such as events or logs. The newsroom plugin's `newsroom.event` uses it.
Both types appear in **AdminCP → Newsroom → Tags** and **Events**, and their edit links carry the UUID or the decimal string, such as `/admin/content/newsroom/event/9007199254740994/edit`.
### Why bigint ids are strings [#why-bigint-ids-are-strings]
A JavaScript number holds integers exactly only up to 2^53 − 1 (`9007199254740991`). A bigint key can be much larger, and a larger id read as a number is silently rounded to a different record: `Number("9007199254740993")` is `9007199254740992`. VitNode never converts a bigint id through `Number`. Drizzle reads the column in `string` mode, and every API, event, cursor and AdminCP URL carries the exact decimal string.
Once the `newsroom_events` id sequence is past 2^53, the public API still returns every id intact:
```bash
curl "http://localhost:3000/api/newsroom/content/events/big-launch"
```
```json title="Response (trimmed)"
{
"id": "9007199254740994",
"title": "Big launch",
"slug": "big-launch",
"primaryTag": { "id": "047d2c6c-1d86-47e2-bcd3-2df9f5359541" },
"tags": ["047d2c6c-1d86-47e2-bcd3-2df9f5359541"]
}
```
`primaryTag` and `tags` point at `newsroom.tag` records, so they carry UUIDs. Keep bigint ids as strings in your own code too.
## Valid ids [#valid-ids]
Every route that takes an id parses it with the content type's strategy before touching the database. Anything else answers `400`, never a database error:
| Strategy | Accepted | Refused, for example |
| -------- | ---------------------------------------------------------------------------------------- | -------------------------------------- |
| `serial` | A positive integer up to 2,147,483,647, or its digits in a URL | `abc`, `0012`, `-1` |
| `bigint` | Positive decimal digits up to 9,223,372,036,854,775,807, without a sign or leading zeros | `0012`, `-1`, `9223372036854775808` |
| `uuid` | Lowercase, hyphenated 8-4-4-4-12 hex | An uppercase UUID, `not-a-uuid`, `123` |
Each record has exactly one spelling, so one record is never cached or indexed under two keys.
## Where ids appear [#where-ids-appear]
Every Content Engine feature works with all three strategies: the public API, the AdminCP lists, editors, pickers and edit links, [public pages](/docs/content-engine/public-pages) and sitemaps, previews, schedules, revisions, [live editing](/docs/content-engine/live-editing), events, search, pagination cursors, [duplicate](/docs/content-engine/duplicate-content) and [hide](/docs/content-engine/content-visibility).
- **Relations** use the key type of the record they point at. A bigint event that links to uuid tags gets a `uuid` foreign key and a `bigint`-to-`uuid` junction table. See [Relations across id strategies](/docs/content-engine/relations-advanced#relations-across-id-strategies).
- **Shared core tables** that hold records of any content type, such as revisions, schedules, slug history, live editing drafts and the search index, store the id as text in a `varchar(64)` `itemId` column. See [Migrations](/docs/content-engine/database#ids-and-shared-tables).
- **Events** type `contentId` by strategy: `number` for serial, `string` for uuid and bigint.
- **Sitemaps** page through records in key order. For a uuid content type that order is lexical, not creation order, and every record still appears once.
- **Repeatable rows** keep their own `serial` ids, whatever the owner uses. User and file references stay integers.
## Helpers [#helpers]
Import these from `@vitnode/core/content` when your own code handles ids:
| Helper | Returns | Use it to |
| -------------------------------------- | -------------------- | ---------------------------------------------------------------------------- |
| `ContentIdOf` | `number` or `string` | Type an id of one content type |
| `ContentId` | `number \| string` | Type an id in code that handles any content type |
| `parseContentIdOf(definition, value)` | The id, or `null` | Validate an id from a request, a job payload or a URL |
| `parseContentId(strategy, value)` | The id, or `null` | The same, when you hold only the strategy |
| `contentIdParamSchema(strategy)` | A Zod schema | Validate a path or query parameter. A serial id becomes a number |
| `contentIdSchema(strategy)` | A Zod schema | Validate an id inside a JSON body |
| `contentAnyIdSchema` | A Zod schema | Accept an id of any strategy, never rounding a bigint |
| `contentIdKey(id)` | `string` | Store an id in a text column, cache key or log. Serial ids keep their digits |
| `contentIdFromKey(strategy, key)` | The id, or `null` | Turn a stored key back into an id |
| `compareContentIds(strategy, a, b)` | `number` | Sort ids the way Postgres does |
`CONTENT_SERIAL_MAX` (`2147483647`) and `CONTENT_BIGINT_MAX` (`"9223372036854775807"`) are exported too. A custom route that reads an id is shown in [Services](/docs/content-engine/services#ids-from-a-url).
## Change the strategy later [#change-the-strategy-later]
The strategy is part of the table's schema, and the engine does not convert existing data. Don't change `idStrategy` on a content type that has records and then run `db:migrate`. The generated SQL cannot turn integer keys into UUIDs.
To switch a live content type, write the data migration yourself:
1. Add the new key column and fill it for every row.
2. Convert every column that references the old key: to-one relation columns in other content types, junction tables (`itemId` and `relatedItemId`), the translations table's `itemId` and repeatable child tables' `itemId`.
3. Rewrite the keys stored for that content type in the shared tables: `core_content_revisions`, `core_content_schedules`, `core_content_slug_history`, `core_search_index`, `core_content_drafts`, `core_content_field_locks`, `core_content_documents` and `core_ai_translation_sources`.
4. Swap the primary key and foreign key constraints, then change `idStrategy` and check that generating migrations again produces no further changes.
Old URLs and API clients that stored the previous ids stop working, so plan redirects if ids appear in public URLs. Creating a new content type and copying the records into it is often simpler.
# Introduction (/docs/content-engine)
The Content Engine turns one TypeScript definition into structured content for your plugin. You describe the fields of a content type, such as an article, and VitNode generates its database table, validation, staff API routes, staff permissions and AdminCP screens. Optional blocks add drafts, a public API, member writing, reports, comments, revisions and more.
## Start here [#start-here]
The beginner tutorial builds one small newsroom, step by step, with an article that has a title, a slug and a body. Each page continues the previous one:
1. [First content type](/docs/content-engine/create-a-content-type): define the article and manage it in the AdminCP.
2. [Drafts & publishing](/docs/content-engine/publication): keep unfinished articles private until staff publish them.
3. [Public API](/docs/content-engine/public-api): let anyone read published articles, and only the fields you choose.
4. [Content list](/docs/content-engine/public-lists): show the articles at `/news`, a page at a time.
5. [Content page](/docs/content-engine/public-pages): give every article its own page at `/news/:slug`.
After that, [Embedded list](/docs/content-engine/public-lists-embed) puts the newest articles under each one, and every guide below builds on the same article.
## What is generated and what you write [#what-is-generated-and-what-you-write]
The Content Engine owns the data and the rules, and your plugin owns every page readers see:
| You build | The Content Engine provides | Your plugin writes |
| --- | --- | --- |
| The AdminCP screen | The list, search, sorting, create and edit forms, publish and hide actions | The sidebar link and, optionally, [custom cells or form layouts](/docs/content-engine/admincp) |
| A list page | The list route, `defineContentList`, `contentListQueryOptions`, `ContentListResults`, `ContentListPagination` | The route, the row layout and the labels |
| A record page | Slug resolution, `404`s, redirects and metadata through `contentDeliveryPage` | The page component, with `RichTextContent` for rich text |
| A member form | The write routes, ownership, validation, `useContentPublicWrite` | The fields with `AutoForm`, success messages and navigation |
| Edit and Report buttons | `canEdit` and `canReport` per visitor, `useContentPermissions`, `ReportButton` | Where the buttons go |
| Comments | The thread route and its placement rules | The comment section, its composer and its refresh |
The page helpers come from `@vitnode/core/tanstack/content`, and every request goes through the typed [`fetcher`](/docs/dev/fetcher) with `module: "content/"`. Public pages are the same for every reader, so they can be cached. The browser asks for anything that depends on the visitor, such as an **Edit** button, and the server checks every write again.
## Add a feature [#add-a-feature]
Each guide starts from a content type you already have, says what it needs at the top, and ends with something you can try. [Reports](/docs/content-engine/reports) and [Relations](/docs/content-engine/relations), for example, only need the beginner path. Comments also need [Member writing](/docs/content-engine/public-write).
| Area | Guides |
| --- | --- |
| Public content | [Embedded list](/docs/content-engine/public-lists-embed) |
| Member content | [Member writing](/docs/content-engine/public-write), [Create form](/docs/content-engine/public-write-frontend), [Edit form](/docs/content-engine/public-write-edit), [Permissions](/docs/content-engine/public-permissions) |
| Interactions | [Reports](/docs/content-engine/reports), [Comments](/docs/content-engine/threads), [Comment actions](/docs/content-engine/threads-editing), [Replies](/docs/content-engine/threads-frontend) |
| Organization | [Relations](/docs/content-engine/relations), [Advanced fields](/docs/content-engine/relations-advanced), [Containers](/docs/content-engine/containers), [Container pages](/docs/content-engine/container-frontend) |
| Moderation | [Approvals](/docs/content-engine/approvals), [Approval notices](/docs/content-engine/approval-notices), [Publishing rules](/docs/content-engine/container-policies), [Visibility](/docs/content-engine/content-visibility) |
| Content features | [Rich text](/docs/content-engine/rich-text), [Translations](/docs/content-engine/localization), [Search](/docs/content-engine/search), [SEO](/docs/content-engine/seo) |
| Editorial | [Revisions](/docs/content-engine/editorial), [Previews](/docs/content-engine/editorial-previews), [Scheduling](/docs/content-engine/editorial-scheduling), [Live editing](/docs/content-engine/live-editing), [Duplication](/docs/content-engine/duplicate-content) |
| Customization | [AdminCP](/docs/content-engine/admincp), [Services](/docs/content-engine/services), [Events](/docs/content-engine/events) |
| Deployment | [Migrations](/docs/content-engine/database), [Caching](/docs/content-engine/caching), [Production](/docs/content-engine/production) |
## What each option adds [#what-each-option-adds]
| From the definition | VitNode generates |
| ------------------- | -------------------------------------------------------------------------------------- |
| `fields` | A Postgres table with system columns and indexes, Zod schemas and a typed service |
| `admin` | An AdminCP list with search, sorting and bulk actions, plus create and edit forms |
| Every content type | Staff routes and the `can_view`, `can_create`, `can_edit` and `can_delete` permissions |
| `publication` | Draft and published states, a `can_publish` permission and **Publish** buttons |
| `publicApi` | Read-only public routes that return only the fields you list |
| `publicWrite` | Create and edit routes for signed-in members, with server-set ownership |
| `reports` | A **Report** button readers use and a moderators' queue |
| `thread` | Nested replies with a route that returns the tree a page at a time |
| `delivery` | Page URLs, SEO metadata, slug redirects and sitemap entries |
| `editorial` | Revisions with restore, preview links and scheduling |
| `liveEditing` | Field locks, an autosaved shared draft and presence in the AdminCP edit form |
| `localization` | A translations table and per-language fields and publishing |
| `search` | Records in the site [search](/docs/content-engine/search) index |
| `visibility` | **Hide** and **Unhide** actions and a `can_hide` permission |
| `duplication` | A **Duplicate** action that copies a record into a new draft |
Content types live in code and in your migrations, not in the database. There is no screen for creating a content type at runtime.
## Reference [#reference]
- [Options](/docs/content-engine/reference): every `defineContentType` option and how the options depend on each other.
- [Fields](/docs/content-engine/fields): every `field.*` helper with its options, column type and form control.
- [Plugin files](/docs/content-engine/plugin-files): the files and exports the app and the API read from your plugin.
# Live editing API (/docs/content-engine/live-editing-api)
The AdminCP drives [live editing](/docs/content-engine/live-editing) for you. This page is for the cases where you need the details: deploying it, calling its routes from your own code, or building a form layout that shows who is editing. Examples use `newsroom.story`, whose staff API lives at `/api/newsroom/admin/content/story`.
## Deployment requirements [#deployment-requirements]
Live editing runs on two channels. Field locks and the shared draft are plain HTTP routes, so they work everywhere. Presence and rich text co-editing travel over the [WebSocket](/docs/dev/websocket) at `/api/ws`, which a standalone API server or a single app with the [Nitro WebSocket route](/docs/dev/websocket/setup) provides, on [Vercel](/docs/dev/deployments/cloud/vercel) too.
| Deployment | Field locks and autosave | Presence | Rich text |
| --------------------------------------------- | ---------------------------- | -------- | ----------------------------------------------- |
| WebSocket at `/api/ws` | Live, pushed over the socket | Yes | Co-edited |
| No WebSocket, or while the socket reconnects | Polled over HTTP every 10 s | No | One editor at a time, locked like a plain field |
After a reconnect each editor joins the room again, reloads the locks and the draft, and reopens its rich text documents, which fetches the edits it missed.
A form without a socket polls `GET /{id}/locks` and `GET /{id}/draft` every 10 seconds, on top of lock renewals. Every request counts against the [rate limiter](/docs/dev/advanced/rate-limiter), which is keyed by IP address: the polls against the read budget (300 a minute), lock renewals and draft saves against the write budget (60 a minute). A newsroom behind one office IP can reach the write budget. A refused lock request leaves the field without autosave, so raise `rateLimiter.write.points` if that is you.
With more than one API instance, set `REDIS_URL`. Instances share presence and document updates over Redis pub/sub. Without it, editors connected to different instances do not see each other.
## HTTP routes [#http-routes]
The routes live under the content type's staff API module. Every route needs an AdminCP session and the type's `can_edit` permission, and answers `404` for a record that does not exist.
| Method and path | Body | Success | Errors |
| -------------------------- | --------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- |
| `GET /{id}/locks` | | `{ locks }`, the unexpired locks | |
| `POST /{id}/locks` | `{ field, locale, action }` | `{ lock }`, or `{ lock: null }` on release | `409` `CONTENT_FIELD_LOCKED`, `400` for an unknown field or wrong locale |
| `GET /{id}/draft` | | `{ shared, translations }` | |
| `PUT /{id}/draft` | `{ locale, values }` | `{ updatedAt }` | `409` `CONTENT_FIELD_NOT_LOCKED`, `400` `CONTENT_DRAFT_WRONG_SCOPE` or `CONTENT_DRAFT_INVALID` |
| `POST /{id}/draft/discard` | `{}` | `{ discarded: true }`, and a `reset` with reason `discarded` to the room | |
- `action` is `acquire`, `renew` or `release`.
- `locale` is `null` for a field that is not localized and an enabled language code for a localized one. A shared field and a localized field never share a draft write.
- A draft write accepts only fields you currently hold a lock on, and validates each value with the field's own rules. It never touches the record; **Save** does that.
Taking a lock on the excerpt:
```http title="Request"
POST /api/newsroom/admin/content/story/2/locks
Content-Type: application/json
{ "field": "excerpt", "locale": null, "action": "acquire" }
```
```json title="200"
{
"lock": {
"expiresAt": "2026-10-10T11:12:14.701Z",
"field": "excerpt",
"locale": null,
"user": { "id": 16, "name": "Anna Kowalska" }
}
}
```
When someone else asks for the same field, the `409` names the holder:
```json title="409"
{
"code": "CONTENT_FIELD_LOCKED",
"lock": {
"expiresAt": "2026-10-10T11:12:14.701Z",
"field": "excerpt",
"locale": null,
"user": { "id": 16, "name": "Anna Kowalska" }
}
}
```
Reading the draft returns the shared fields and one draft per language:
```json title="GET /api/newsroom/admin/content/story/2/draft"
{
"shared": {
"baseVersion": 3,
"updatedAt": "2026-10-10T10:57:20.381Z",
"updatedBy": { "id": 16, "name": "Anna Kowalska" },
"values": { "title": "Spring menu launches Monday at noon" }
},
"translations": {}
}
```
`baseVersion` is the record or translation version the draft was written on.
## WebSocket channel [#websocket-channel]
The socket side is one channel, `@vitnode/core_content_live`, on the shared `/api/ws` connection. Joining a record's room checks the same AdminCP session and `can_edit` as the HTTP routes. Every message carries the record as `{ contentTypeId, itemId }`, and every client message carries the `clientId` of the tab that sent it.
| Direction | Messages |
| --------- | --------------------------------------------------------------------------------------------------------------------------- |
| Client | `join`, `focus`, `heartbeat`, `leave`, and `doc:open`, `doc:update`, `doc:awareness`, `doc:close` for rich text |
| Server | `joined`, `presence`, `locks`, `draft`, `reset`, `error`, and `doc:seed`, `doc:state-vector`, `doc:update`, `doc:awareness` |
Rich text documents are [Yjs](https://yjs.dev) documents, one per record, field and language. Updates travel as base64. The protocol types live in `@vitnode/core/content/live/protocol` if you need them, but the AdminCP is the only client you should need.
## Timings [#timings]
| What | Value |
| ----------------------------------------------- | ---------- |
| Lock lifetime without renewal | 60 s |
| Lock renewal while the field has focus | every 20 s |
| Autosave after the last keystroke | 1.5 s |
| Presence heartbeat | every 15 s |
| Member dropped after missed heartbeats | 45 s |
| Rich text document stored after the last change | 2 s |
| Polling without a socket | every 10 s |
| Untouched drafts and documents removed after | 30 days |
## Where the data lives [#where-the-data-lives]
| Table | Holds |
| -------------------------- | ----------------------------------------------------------------- |
| `core_content_drafts` | The shared draft of plain fields, one row per record and language |
| `core_content_field_locks` | Active field locks with their holder and expiry |
| `core_content_documents` | The Yjs state of each rich text field, per record and language |
Each table keys the record by its id as text in a `varchar(64)` `itemId`, so live editing works with every [id strategy](/docs/content-engine/id-strategy). The socket accepts a uuid or bigint id and checks it against the content type's strategy, refusing a malformed one.
The daily `content-editorial-cleanup` [cron job](/docs/dev/cron) removes expired locks, documents untouched for 30 days, and drafts untouched for 30 days whose record has moved on since. A stale draft whose record has not changed is kept, because it is somebody's unsaved work. When an editor's last tab leaves a record, their locks go too.
## Use live state in a custom form layout [#use-live-state-in-a-custom-form-layout]
A plugin that replaces the edit form with [its own layout](/docs/content-engine/admincp) still gets locks and outlines on every field it renders with `ContentFormField`. The rest of the live UI comes from `@vitnode/core/content/admin-form`:
```tsx title="story-form-layout.tsx"
import {
ContentFormField,
ContentLivePresence,
ContentLiveStatus,
} from "@vitnode/core/content/admin-form";
export const StoryFormLayout = () => (
);
```
Register it with `forms: { layout: StoryFormLayout }` in the type's `contentTypeAdmin(...)` entry, the way the blog plugin registers `BlogArticleFormLayout`.
| Export | What it gives you |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ContentLivePresence` | Avatars of everyone else in the record. `max` sets how many show before **+N**, 5 by default |
| `ContentLiveFieldPresence` | Avatars of the people in one `field` and `locale` |
| `ContentLiveLanguagePresence` | Who is working in one `locale` |
| `ContentLiveStatus` | The autosave state: **Saving…**, **Autosaved 5 minutes ago** (with an amber dot while the draft is not saved into the record), **Autosave failed** |
| `useContentLive()` | The session: `session.members`, `session.locks`, `status` (`saving`, `savedAt`, `failed`, `dirty`) and `coEditing` |
| `useContentRichTextReplace()` | `(field, locale, document) => void` that replaces a rich text field through the shared editor, so everyone sees it and it can be undone. `null` while rich text is not co-edited |
All of them render nothing, or return `null`, outside a live form, so the same layout works for the create form.
# Live editing (/docs/content-engine/live-editing)
Live editing lets a team work on the same record at the same time without overwriting each other. Changes autosave to a shared draft, everyone sees who is in which field, plain fields are edited by one person at a time, and [rich text](/docs/content-engine/rich-text) fields are typed in together.
## Turn it on [#turn-it-on]
Add `liveEditing: true` next to [`editorial`](/docs/content-engine/editorial). Live editing needs `editorial`, because field locks and the shared draft are measured against the record version it adds. Without it, `defineContentType` throws ``liveEditing needs `editorial` ``, and TypeScript flags the option first:
```ts title="plugins/newsroom/src/content/story.ts (excerpt)"
export const storyContentType = defineContentType({
id: "newsroom.story",
tableName: "newsroom_stories",
// ...
editorial: {
revisions: { retention: 20 },
preview: { expiresInMinutes: 30 },
scheduling: true,
},
liveEditing: true, // [!code highlight]
// ...
});
```
A live session starts when someone opens an existing record's edit form in the AdminCP. That needs three things:
- An AdminCP session, from signing in at `/admin`.
- The content type's `can_edit` permission. Someone who can only view the record does not join.
- A saved record. The create form is not live, because there is nothing to share yet.
Presence and rich text co-editing also need the API's [WebSocket](/docs/dev/websocket). Without it, autosave and field locks still work over HTTP, a little slower. [Deployment requirements](/docs/content-engine/live-editing-api#deployment-requirements) lists what each setup gets.
## What editors see [#what-editors-see]
### Presence [#presence]
The form header shows an avatar for everyone else in the record, up to five and then **+N**. Hover or focus an avatar to read where that person is, such as "editing Title". A ring in their color means they are in a field right now.
The field they are in gets an outline in their color with a name tag. When they move to another field, the outline glides after them, and nothing on the page shifts to make room. In a localized form, the language switcher marks the languages people are working in. You never see yourself, and one person in several tabs counts once.
### Field locks [#field-locks]
Clicking into a plain field, such as a title, slug or category, takes a lock on that field in that language. Everyone else sees the field dimmed and read-only inside the editor's outline, and the value updates as they type. Screen readers announce "Anna Kowalska is editing".
A lock lasts 60 seconds and renews every 20 seconds while the editor stays in the field. Leaving the field releases it, and so does closing the record. A lock nobody renews, say because a laptop went to sleep, expires on its own.
### Autosave and the shared draft [#autosave-and-the-shared-draft]
About 1.5 seconds after you stop typing in a field you hold, the value is saved to the record's draft. Close the tab and it's still there, but readers don't see it yet. The header shows **Saving…** and then **Autosaved just now**, later **Autosaved 5 minutes ago**, or **Autosave failed** when the write failed. An amber dot in front means the draft holds changes the record doesn't have yet, and it stays until someone clicks **Save changes**. Hover it for a reminder.
Changed your mind? **Discard** next to the autosave time throws the draft away after you confirm, and the form goes back to the last saved version. It is a team draft, so everyone editing the record goes back too, and they get a short note saying so.
There is one draft per record and language, shared by the whole team. When you open the record, you see the draft, not only what was last saved. **Save** commits it through the usual [version check](/docs/content-engine/editorial#safe-concurrent-edits) and creates one revision. Autosave itself never creates revisions, emits no events and leaves search and caches alone. [Preview links](/docs/content-engine/editorial-previews) also ignore the draft until someone saves.
### Rich text co-editing [#rich-text-co-editing]
Rich text fields are not locked and get no outline. Everyone in the same field and language types into one shared document and sees each other's caret with a name tag, plus a tint over the text they select. Undo only undoes your own changes. The newsroom plugin's story has no rich text field, so this is the blog plugin's article editor:
Each language has its own shared document. The first person to open a field fills it from the record. If the connection drops, the editor keeps what you type and sends it when the connection comes back. The server stores the document about two seconds after the last change, and **Save** writes its current content, everyone's edits included, to the record.
### Restores and deletes [#restores-and-deletes]
Restoring a revision or deleting the record throws away its drafts, locks and shared documents. Everyone in the session gets a notice, and the form reloads with the new state.
## Check the result [#check-the-result]
1. Sign in at `/admin` as two staff members with `can_edit`, for example in two browser profiles.
2. Open the same record's edit form in both.
3. Click into **Title** in one window. The other window shows the outline and name tag, and the field turns read-only there.
4. Type a few words and wait two seconds. The other window shows the new value, and the header of the first says **Autosaved just now**.
Building your own form layout, or calling the lock and draft routes yourself? See the [live editing API](/docs/content-engine/live-editing-api).
# Live refresh (/docs/content-engine/live-refresh)
Live refresh keeps screens that show Content Engine records current without a reload. Every generated AdminCP list takes part on its own, and a comment section joins in with [Live comments](/docs/content-engine/threads-live). Both use the app's one [WebSocket](/docs/dev/websocket) connection; nothing opens a second one.
The WebSocket only carries small hints, such as "this list changed" or "this branch of this thread changed". Each open screen then reads the data again over HTTP with the viewer's own session. That costs one extra request per change, and buys a simple rule: what a reader sees always comes from the same routes and checks as a first load.
## AdminCP lists [#admincp-lists]
Every generated list joins its content type's room while it's on screen, with no configuration. When a record of that type changes in another tab or session (created, edited, published, hidden, deleted, duplicated, scheduled, or one of its translations changed), the list:
- reads the page on screen again, with its filters, search, sorting and page number, and keeps the old rows on screen meanwhile;
- forgets the cached pages nobody is looking at, so opening one later reads it fresh;
- keeps selected rows that are still on the page and drops the ones that left it;
- collects a burst of changes into one read, 0.4 seconds after the last change and never more than 2 seconds after the first;
- shows **Could not refresh this list** with **Try again** when that read fails, and keeps the rows.
A delete can push the current page past the end. The list route answers with the last page instead, so the list doesn't end up empty.
## What sends a signal [#what-sends-a-signal]
Signals come from `emitContentEvent`, which every generated route and service effect calls once a write has committed. It works in this order:
1. The transaction commits. A write that rolls back never gets further.
2. The content event is emitted, and the content type's cached pages and public reads are expired.
3. The signals are published.
So whoever reads again because of a signal gets the new state, never a cached copy.
| Room | Who may join | Sent for |
| --- | --- | --- |
| AdminCP list of one content type | An AdminCP session with the content type's `can_view`, the permission of the list route | Every content event of that type |
| Thread of one comment type under one root record | Anyone who may read that thread: guests for a public article; authors, editors and moderators for a hidden one | Changes to comments that were or are public, naming the top-level branch they sit in |
| The same thread room | The same | The root record being hidden, unhidden, published, unpublished, restored or deleted |
A thread signal never carries text, authors or reasons. It is sent only for a comment that was or is public, so a draft, a comment waiting for a moderator, or an edit of a hidden comment sends nothing to the thread. The AdminCP list still hears about it.
### Custom write routes [#custom-write-routes]
A custom route that writes through `model.service(c)` or `model.editorialService(c)` emits nothing by itself, so open screens don't hear about it. After the write commits, call `contentEditorialEffects` for an editorial write, or `emitContentEvent` for a plain one, as the generated routes do. Pass the row whenever you have it. For a delete of a threaded record it's required, because the deleted record can't be read back to find its thread:
```ts title="plugins/newsroom/src/api/modules/comments/routes/remove.route.ts (excerpt)"
import {
contentPublicStateOf,
emitContentEvent,
} from "@vitnode/core/content/server";
import { commentContentType } from "@/content/comment";
import { commentContent } from "@/database/comments";
import { manifest } from "@/manifest.gen";
// Inside your route handler, after the write:
const row = await commentContent.service(c).delete(id);
if (row) {
await emitContentEvent(
c,
commentContentType,
"deleted",
{ contentId: row.id },
{
pluginId: manifest.id,
publicState: contentPublicStateOf(commentContentType, row, null),
row,
},
);
}
```
For a change that has no content event, `publishContentRefresh(c, { action, contentId, definition, publicState, row })` from the same import sends only the signals. Call it after the caches are expired.
## Who stays subscribed [#who-stays-subscribed]
A room name is only an address. The server checks every join with the rules above and answers `FORBIDDEN` or `NOT_FOUND` without adding the connection. After that:
- **A revoked session** (signing out a device, a password change or reset, an admin revoke) closes the user's WebSocket connections on every instance. **Signing out or in** within a tab reconnects the shared connection under the new identity. Either way, the tabs join their rooms again and the server checks them again.
- **A lost permission or an ended session**, including an AdminCP session that expired or signed out, is caught within about 80 seconds: the server checks every subscription again once it's a minute old. A thread subscription opened while signed in fails that check once its session is gone, even on a public article.
- **A thread root that becomes hidden, unpublished or deleted** is checked at once. Readers who lost access are removed from the room, and their open thread reads again, gets `404` and clears.
Tabs of one browser share the connection, but each tab joins for itself and acts only on its own confirmed joins. A tab with the comments closed doesn't react to a signal another tab asked for.
## Reconnects and missed changes [#reconnects-and-missed-changes]
Delivery is best effort and nothing is replayed. A signal sent while a tab was disconnected is lost, so every join is followed by one read that covers the gap:
- an AdminCP list reads its page once;
- a comment section reads its loaded pages once.
After a reconnect, that read waits a random moment of up to 1.5 seconds, so a server restart doesn't make every open tab read at the same time.
## Several server instances [#several-server-instances]
With `REDIS_URL` set, a signal published on one instance reaches subscribers on every instance, and a root change re-checks their rooms there too. Without Redis, only tabs connected to the instance that handled the write hear about it, which is fine for a single server. See [Rooms on several instances](/docs/dev/websocket/rooms#rooms-on-several-instances).
## Cost of a busy thread [#cost-of-a-busy-thread]
A popular article can have hundreds of readers with its thread open, and every signal reaches all of them, so each one has to stay cheap. Per open section:
| Event | Requests |
| --- | --- |
| A change in a loaded branch | One `GET /thread/branches` for that branch |
| Five quick changes to the same branch | One, within 2 seconds |
| Changes to several loaded branches at once | One per 10 branches, at most 2 running at once |
| A new top-level comment | None until **Show new comments**, then one `GET /thread` for what follows the last loaded comment |
| A change in a branch that isn't loaded | None |
| A join or reconnect | One read of every loaded page |
Guests and readers without hidden access all get the same branch answer, so the API serves it from its [public read cache](/docs/content-engine/caching), which the write expired before the signal went out. Readers who may see hidden comments get a private answer that is never shared.
Limits: one connection holds at most 64 subscriptions across all of its tabs and may send 120 joins a minute, and `/thread/branches` reads at most 10 branches per request. These are limits in the code, not benchmark results.
## Follow a scope from your own screen [#follow-a-scope-from-your-own-screen]
`useContentLiveRefresh` from `@vitnode/core/tanstack/content` is the hook behind both features. Use it when your own screen shows Content Engine data, such as a custom admin page. Pass a scope and re-read on every signal and every join:
```tsx title="plugins/newsroom/src/views/story-board.tsx (excerpt)"
import { useContentLiveRefresh } from "@vitnode/core/tanstack/content";
import { storyContentType } from "@/content/story";
// Inside the component, next to the query that loads the board:
const status = useContentLiveRefresh(
{ contentTypeId: storyContentType.id, kind: "admin" },
{
onSignal: () => void refetch(),
onSubscribed: () => void refetch(),
},
);
```
`refetch` is the refetch of the screen's own TanStack Query. A scope is `{ contentTypeId, kind: "admin" }` or `{ contentTypeId, kind: "thread", rootId }`, with the same join rules as the table above. Pass `null` to stay off. The hook returns `"off"` (no scope or no open connection), `"joining"`, `"live"` or `"denied"` (refused or revoked), and calls `onDenied` when the server refuses or revokes the subscription.
## Limitations [#limitations]
- Signals are hints, not a durable log. A reader who was offline catches up on the next join, not change by change.
- Moderators don't get live updates for changes the public can't see, such as a new comment waiting for approval. They see them on the next read.
- A subscription the server refused or revoked stays off until the connection reconnects or the screen is opened again.
- The Forum plugin draws its own topic thread and doesn't use live comments yet.
## Related [#related]
- [Live comments](/docs/content-engine/threads-live): turn it on for a comment section.
- [Events](/docs/content-engine/events): the content events behind the signals.
- [Reconnects](/docs/dev/websocket/reconnects): what a WebSocket reconnect keeps and loses.
# Translations (/docs/content-engine/localization)
Localization stores chosen fields once per language, while every other field stays shared. A bulletin's title and body get a Polish version, but whether it is featured stays one value. Translated values live in a second table, `{tableName}_translations`, with one row per record and language. This guide uses `newsroom.bulletin` from the newsroom plugin.
## Before you begin [#before-you-begin]
The languages come from your app's `i18n.locales` in `vitnode.config.ts` (see [Languages & Localization](/docs/dev/i18n)) and from the languages created at install. `defaultLocale` must be one of them. A language turned off in the config stays readable in the AdminCP, but nobody can write to it and the public API does not serve it.
### Mark the translatable fields [#mark-the-translatable-fields]
Add a `localization` block and set `localized: true` on each field that changes per language:
```ts title="plugins/newsroom/src/content/bulletin.ts (excerpt)"
export const bulletinContentType = defineContentType({
id: "newsroom.bulletin",
tableName: "newsroom_bulletins",
// [!code ++:4]
localization: {
defaultLocale: "en",
fallback: "default",
},
publication: true,
// ...
fields: {
// [!code highlight:8]
title: field.text({
localized: true,
required: true,
minLength: 3,
maxLength: 200,
}),
slug: field.slug({ localized: true, source: "title" }),
body: field.textarea({ localized: true, required: true }),
featured: field.boolean({ defaultValue: false }),
},
});
```
`text`, `textarea`, `richText`, `slug`, `blocks` and whole `group` fields can be localized. Numbers, booleans, enums, dates, files, users, relations and repeatables are always shared. A slug and its `source` must both be localized or both shared, otherwise every language would get the same URL. `localized: true` without a `localization` block throws, and so does a `localization` block without a localized field.
### Export the translations table [#export-the-translations-table]
```ts title="plugins/newsroom/src/database/bulletins.ts (excerpt)"
export const bulletinContent = createContentModel(bulletinContentType);
export const newsroom_bulletins = bulletinContent.table;
export const newsroom_bulletins_translations = bulletinContent.translationTable; // [!code ++]
```
Drizzle Kit only sees exported tables, so without this line the migration has no translations table.
### Build and migrate [#build-and-migrate]
```bash tab="bun"
bun run db:migrate
```
```bash tab="pnpm"
pnpm db:migrate
```
```bash tab="npm"
npm run db:migrate
```
The localized columns move to `newsroom_bulletins_translations`, keyed by `(itemId, languageId)`. That table has its own `version`, `createdAt` and `updatedAt`, plus `status` and `publishedAt` when the type has publication.
The migration does not copy existing values into the translations table. If
the table already holds records, review the SQL before you apply it and add a
step that copies them.
## Edit languages in the AdminCP [#edit-languages-in-the-admincp]
There are no language tabs. Each localized field carries its own language selector, so an editor can fix the Polish title without leaving the form. The field first shows your AdminCP language if it has text, then the default language, then any language that has text. Shared fields have no selector.
This is the blog plugin's category dialog, where `name` is `field.text({ localized: true })`:
Saving the form sends the shared fields and every language you typed into in one request: `POST /localized` for a new record, `PUT /{id}/localized` for an existing one. The server writes them in one transaction. A new record must include its default language. A Polish-only edit does not touch the shared row, so it does not bump the record's version or expire the English cache.
The first time you type into a language, the save creates that translation, so it needs that language's required fields too. If a new translation (other than the default language) is still missing one, the AdminCP leaves that language out, saves everything else and warns "Polish was not saved: fill in Title in this language to save it." With live editing on, the unfinished translation stays in its draft until you finish it.
When the server refuses a value anyway, nothing is saved. The save answers `400` with a body that names each field and its language, and the AdminCP shows it as "Fill in Title (Polish), then save again.":
```json title="PUT /api/@vitnode/blog/admin/content/posts/5/localized → 400"
{
"code": "CONTENT_INVALID_INPUT",
"contentTypeId": "blog.post",
"issues": [{ "code": "required", "field": "title", "locale": "pl" }]
}
```
`code` is `required` for a missing value and Zod's own issue code (`too_big`, `invalid_format`, …) otherwise. `locale` is `null` for a shared field. Read the body with `parseContentInvalidInput` from `@vitnode/core/content`. Every admin write route answers invalid input this way, not only the localized ones.
With publication, each language has its own status. Publishing the record publishes its languages too, and you can then unpublish one language alone. A translation is public only when both the record and that translation are published, and the record is not [hidden](/docs/content-engine/content-visibility). With `editorial`, each language also keeps its own revisions and preview links.
The newsroom plugin registers `newsroom.bulletin` on the API only, so it has
no AdminCP screen. Add it to the plugin's `adminContent` and `adminNav`
content types to get the generated form shown above.
## Read a language from the public API [#read-a-language-from-the-public-api]
The public API serves one language per request, chosen in this order:
1. The `?locale=` query parameter. A locale that the site does not serve returns `404`.
2. Otherwise the `Accept-Language` header. The response then carries `Vary: Accept-Language`.
3. Otherwise `defaultLocale`.
```bash
curl -i "http://localhost:3000/api/newsroom/content/bulletins/witaj-content-engine?locale=pl"
```
```http
HTTP/1.1 200
content-language: pl
{"title":"Witaj Content Engine","slug":"witaj-content-engine","body":"Jeden rekord, dwa języki.","featured":false,"publishedAt":"2026-10-10T10:57:12.452Z","locale":"pl"}
```
The `locale` property says which language the body is in. When the requested translation is missing or unpublished, `fallback: "default"` serves the default language instead, so `"locale"` becomes `"en"`. With `fallback: "none"` (the default), the API returns `404`.
In a page loader, pass the route's locale through. This is the newsroom plugin's bulletin page:
```ts title="plugins/newsroom/src/pages/bulletin-page.tsx (excerpt)"
const detail = await fetcher({
plugin: manifest.id,
method: "get",
module: "content/bulletins",
path: "/{slug}",
args: {
params: { slug: encodeURIComponent(slug) },
query: { locale },
},
});
```
Opening `/pl/bulletins/witaj-content-engine` renders the Polish translation:
Each translation can have its own slug and URL. [Content page](/docs/content-engine/public-pages) covers localized URLs and `hreflang`.
## Translation routes [#translation-routes]
`buildContentAdminModule` adds staff routes for each language under the content type's admin path. They use the same staff permissions as the record:
| Route | Does |
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| `GET /{id}/translations` | Lists the record's translations |
| `GET`, `POST`, `PUT`, `DELETE /{id}/translations/{locale}` | Reads, creates, updates or deletes one language |
| `POST /{id}/translations/{locale}/publish` and `/unpublish` | Changes one language's status. Needs publication |
| `GET /{id}/translations/{locale}/revisions` | One language's history. Needs editorial |
| `POST /{id}/translations/{locale}/preview` | A preview link for one language. Needs editorial preview |
| `POST /localized`, `PUT /{id}/localized` | Saves shared fields and several languages in one transaction |
Each translation write emits an event such as `content.newsroom.bulletin.translation_created` or `translation_published`, listed in [Events](/docs/content-engine/events).
## Options [#options]
| Name | Type | Required | Default | Description |
| --------------- | ----------------------- | -------- | -------- | ---------------------------------------------------------------------- |
| `defaultLocale` | `string` | Yes | | A language code such as `"en"` or `"pt-BR"`. Every record starts in it |
| `fallback` | `"none"` \| `"default"` | No | `"none"` | What the public API serves when the requested language is missing |
# Notifications API (/docs/content-engine/notifications-api)
This page lists everything `buildContentNotifications` accepts and how its notifications behave. For a guided setup, follow [Notifications](/docs/content-engine/notifications). Examples use `newsroom.comment` and `newsroom.article` from the newsroom plugin.
## `buildContentNotifications()` [#buildcontentnotifications]
```ts title="plugins/newsroom/src/api/lib/notifications.ts"
import { buildContentNotifications } from "@vitnode/core/content/server";
export const commentNotifications = buildContentNotifications({
content: commentContentType,
root: articleContentType,
rules: {
replies: { id: "newsroom.comment_reply", preset: "threadReply" /* ... */ },
},
});
```
Server-only, from `@vitnode/core/content/server`. Register the result in `buildApiPlugin({ contentNotifications: [commentNotifications] })`. Each rule becomes one [notification type](/docs/dev/notifications/notification-types), registered with the plugin.
| Name | Type | Required | Default | Description |
| --------- | ----------------------------- | ----------------- | ------- | ----------- |
| `content` | content type definition | Yes | | The content type whose operations notify. Its model must be registered with `buildContentAdminModule` |
| `root` | content type definition | For `threadReply` | | The type `thread.root` points at. Checked at startup |
| `access` | `({ c, contentId, rootId, userIds }) => number[]` | No | | Narrows who may see every preset notification, for content your plugin restricts to some members. Return the allowed ids, one query per batch |
| `rules` | object of rules | Yes | | At least one. Keys are names in your code only |
It throws `ContentEngineError` when an author field is not a to-one, shared `field.user()`, when `threadReply` is used without `thread` or without `root`, when two rules share an `id`, or when `rules` is empty. An invalid `id` or `category` throws `NotificationRegistryError`. At startup, an unregistered content type or a `root` that is not the `thread.root` target stops the app with a message naming the plugin.
## Options shared by the presets [#options-shared-by-the-presets]
| Name | Type | Required | Default | Description |
| ---------------- | -------------------------------------------------- | -------- | ----------- | ----------- |
| `id` | `string` | Yes | | The notification type id, such as `"newsroom.comment_reply"`: at least two dot-separated segments of `a-z`, `0-9`, `_`, `-`, at most 100 characters |
| `category` | `string` | No | `"content"` | Groups types on the preferences page. `approvalPending` defaults to `"moderation"` |
| `defaults.inApp` | `boolean` | No | `true` | Whether members get it in the bell before choosing |
| `defaults.email` | `"none"` \| `"immediate"` \| `"daily"` \| `"weekly"` | No | `"none"` | Email before choosing. Anything but `"none"` enables email for the type |
| `email` | `boolean` | No | `false` | Allows email so members can opt in while the default stays `"none"` |
### Stable ids [#stable-ids]
`id` is stored with every notification event and every member's preference, so it must never change. The key in `rules` is not stored anywhere, so rename it freely. Two rules, in any plugin, cannot share an id.
## `threadReply` preset [#threadreply-preset]
New comments and replies in a thread. Runs on the record's [first publication](#triggers-and-deduplication).
| Name | Type | Required | Default | Description |
| ---------------------------- | -------------------------------------- | -------- | ------- | ----------- |
| `recipients.authorField` | author field of `content` | Yes | | Who wrote the record: excluded from its own notification, and the recipient when someone answers it |
| `recipients.rootAuthorField` | author field of `root` | No | | The root's author, told about every new record in the thread. Omit to skip |
| `recipients.parentAuthor` | `boolean` | No | `true` | Tell the author of the record being answered |
| `messages.label` | API message key | Yes | | The type's name in preferences |
| `messages.description` | API message key | No | | One line under the label |
| `messages.comment` | API message key | Yes | | Title for the root's author. Receives `{actor}` and `{title}` |
| `messages.reply` | API message key | Yes | | Title for the parent's author. Receives `{actor}` and `{title}` |
| `target` | `({ content, parent, root }) => string` | Yes | | Same-site path the notification opens. Called when the notification is sent; the result is stored |
| `title` | `({ content, root }) => string` | No | root's `admin.titleField` | The `{title}` value, cut at 300 characters |
| `grouping.windowMinutes` | `number` | No | off | Merges a member's notifications for the same root and wording into one item within the window (1 to 10080). The item opens the newest one |
Author fields are typed: only to-one, shared `field.user()` names of each content type compile. `content`, `parent` and `root` in `target` are typed rows of their content types.
A member who is both the root's author and the parent's author gets one notification with the `reply` text. The record's author and whoever made it public, such as the moderator who approved it, never receive it. `{actor}` is the record's author, or "Someone" when the account is gone.
Without `rootAuthorField` the rule notifies replies only, so the root type needs no author. `{title}` reads the root's own row, so a localized title field gives an empty string. Leave `{title}` out of the texts or pass `title`.
## `moderationDecision` preset [#moderationdecision-preset]
Tells the submitter of a [moderated](/docs/content-engine/approvals) create or edit what a moderator decided.
| Name | Type | Required | Default | Description |
| ---------------------- | ----------------------------------------------------- | -------- | -------------------------- | ----------- |
| `decisions` | `("approved" \| "rejected")[]` | No | both | Which decisions notify |
| `messages.label` | API message key | Yes | | The type's name in preferences |
| `messages.description` | API message key | No | | One line under the label |
| `messages.approved` | API message key | Yes | | Receives `{title}` and `{kind}` (`create` or `edit`) |
| `messages.rejected` | API message key | Yes | | Receives `{title}`, `{kind}` and `{reason}` (empty without one) |
| `target` | `({ content, decision, root }) => string \| null` | Yes | | Where it leads. A rejected create is a draft, so link somewhere its author can open |
| `title` | `({ content, root }) => string` | No | root's, then the record's `admin.titleField` | The `{title}` value |
The recipient is the submission's `authorId`, which is the person who proposed the change, not necessarily the record's author. The moderator who decided is not named on the notification and is never notified about their own submission. Approving a create also runs the record's first-publication rules; approving an edit does not.
## `approvalPending` preset [#approvalpending-preset]
Tells moderators that a new record or a proposed edit waits in the [approval queue](/docs/dev/moderation/review-approvals), and links to that submission at `/modcp/approvals/{id}`. The Forum plugin registers one for topics and one for comments:
```ts title="plugins/forum/src/api/lib/notifications.ts"
pending: {
id: "forum.topic_pending",
preset: "approvalPending",
messages: {
label: "@vitnode/forum.notifications.topic_pending.label",
description: "@vitnode/forum.notifications.topic_pending.description",
pending: "@vitnode/forum.notifications.topic_pending.pending",
},
},
```
| Name | Type | Required | Default | Description |
| ---------------------- | --------------- | -------- | ------- | ----------- |
| `messages.label` | API message key | Yes | | The type's name in preferences |
| `messages.description` | API message key | No | | One line under the label |
| `messages.pending` | API message key | Yes | | Receives `{kind}` (`create` or `edit`) and `{container}`, the name of the container the record is filed in |
The link is fixed, so there is no `target`, and the text carries no title or body: a moderator who loses access keeps nothing readable about the content. A typical message is `"{kind, select, edit {An edit to a topic is waiting for approval in {container}} other {A new topic is waiting for approval in {container}}}"`.
Recipients are the moderators who could decide the submission: their `can_approve` for the content type, merged from their own entry and their roles, must cover the container the record is filed in, with the same [container scopes](/docs/dev/moderation/scoped-permissions#pick-forums-or-whole-subtrees) the queue uses. Root roles and unrestricted moderator entries qualify everywhere. Being staff, or an administrator, is not enough. Permissions are read from the database when the notification is sent, not from the staff permission cache, and the submitter is never told about their own submission. At most 1000 permission holders are considered per submission; past that, the rest are skipped with a warning in the logs.
The preset only applies to content types whose container collection has [publishing policies](/docs/content-engine/container-policies) and whose `publicWrite` is on, because the queue lists nothing else.
## Custom rules [#custom-rules]
A rule with `type` instead of `preset` publishes an existing notification type on a supported trigger:
```ts title="plugins/newsroom/src/api/lib/notifications.ts"
import {
contentNotificationAccess,
contentNotificationRefs,
} from "@vitnode/core/content/server";
import { buildNotificationType } from "@vitnode/core/api/lib/notifications/registry";
import { z } from "zod";
const deskCommentNotification = buildNotificationType({
id: "newsroom.desk_comment",
version: 1,
schema: z.object({
contentId: z.string(),
contentTypeId: z.string(),
rootId: z.string().nullable(),
target: z.string(),
}),
category: "content",
label: "newsroom.notifications.desk_comment.label",
defaults: { inApp: true, email: "none" },
access: contentNotificationAccess({ content: commentContentType, policy: "content" }),
present: ({ data, t }) => ({
title: t("newsroom.notifications.desk_comment.title"),
target: data.target,
}),
});
// In buildContentNotifications({ ..., rules }):
deskEditors: {
type: deskCommentNotification,
on: "firstPublication",
// Your own query: the user ids that should hear about it.
recipients: async ({ c, root }) => await findDeskEditorIds(c, root),
data: context => ({
...contentNotificationRefs(context),
target: `/news/${String(context.root?.slug)}#comment-${String(context.content.id)}`,
}),
},
```
| Name | Type | Required | Default | Description |
| ------------ | ------------------------------------------ | -------- | ------- | ----------- |
| `type` | `buildNotificationType()` result | Yes | | Registered for you; listing it in `notificationTypes` as well is fine |
| `on` | `"firstPublication"` \| `"moderationDecision"` | Yes | | The [trigger](#triggers-and-deduplication) |
| `recipients` | `(context) => (number \| null \| undefined)[]` | Yes | | Candidate user ids. `null`s and duplicates are dropped, and so is the actor unless `allowSelf` |
| `data` | `(context) => TData` | Yes | | Data for the type's `schema`, typed from it |
| `allowSelf` | `boolean` | No | `false` | Let the actor receive it |
`context` holds `content`, `parent` and `root` (typed rows, reloaded when the notification is sent), `decision` (for `moderationDecision`: `submissionId`, `status`, `kind`, `authorId`, `reviewerId`, `reason`), `actorId`, `trigger`, `contentTypeId` and `c`. `c` is the background worker's context. The database works, but there is no signed-in user.
`recipients` and `data` can run more than once for one operation, because the worker retries after a failure. Keep them free of side effects: read and compute, never send email, call webhooks or write rows. Anything they throw retries the whole operation.
Give a custom type `access: contentNotificationAccess({ content, policy })` and spread `contentNotificationRefs(context)` into its data, so core can check the record again later. Without it, only the type's own `access` (or none) applies.
## Triggers and deduplication [#triggers-and-deduplication]
Two different things decide whether something is sent twice:
- **Retrying one operation** never duplicates anything. Each publication carries a key built from the operation (`first-publication:{contentTypeId}:{id}:{relation}` or `decision:{contentTypeId}:{submissionId}` or `approval:{contentTypeId}:{submissionId}`), and core stores at most one event per type and key, enforced by a unique index. A worker that publishes and then crashes before finishing finds the same event on its retry.
- **Separate operations** notify again only when the trigger allows it:
| Trigger | Runs | Again later? |
| --- | --- | --- |
| `firstPublication` | When the record becomes public for the first time: a published create, a publish, a scheduled publish when it fires, or the approval of a create | Never. Unpublishing and republishing, hiding and showing, restoring a revision and editing do not run it |
| `moderationDecision` | When a moderator approves or rejects a submission | Once per submission, so each review cycle can notify |
| `approvalSubmitted` (`approvalPending` only) | When a submission starts waiting: a pending create, an edit proposal, or a newer proposal that replaces one | Once per submission, so a resubmission after a rejection notifies again |
VitNode recognises the first publication inside the publishing transaction, where the record's `publishedAt` is still `NULL` under the row lock. Once set, VitNode never rewrites it. That state lives on the record itself, not in anyone's inbox, so deleting a notification or the passing of time cannot make a comment notify again. Content published before the rules existed already has a `publishedAt`, so adding rules sends nothing for it, and no migration or backfill is needed.
## Access [#access]
Core checks a notification type's `access` before delivering it, before every immediate or digest email and every time an inbox loads. Presets use `contentNotificationAccess`:
| Policy | A member may see it while |
| --- | --- |
| `"content"` (`threadReply`) | The record and its root exist and are public: published, not hidden, not scheduled for later. For a reply, the comment it answers still exists |
| `"submission"` (`moderationDecision`) | The member is the submission's author, the submission still has that decision and the record exists. An approval also needs the record to be public; a rejection does not. The root must stay public |
| `"approval"` (`approvalPending`) | The submission is still pending, the record exists, and the member holds `can_approve` both for the container the queue lists the submission under and for the one the record is filed in now. The record does not have to be public |
A notification that fails the check shows "This notification is no longer available", with no title, text or link, and its email is skipped. Content Engine reads are not role-based, so add `access` to `buildContentNotifications` when your plugin limits content to some members. An email that was already sent cannot be taken back.
## Delivery and retries [#delivery-and-retries]
1. The operation commits. In the same transaction VitNode stored an **intent**: a `content-notifications` task in `core_queue` holding only ids and the facts of the operation (who acted, which decision). A rolled-back operation leaves no intent. An existing transaction is joined, never committed early.
2. Right after the response, or on the next run of the queue cron, a worker claims the task (`FOR UPDATE SKIP LOCKED`, so two workers never take the same one), reloads the records and checks they are still public.
3. It resolves recipients, calls your callbacks and publishes every notification of the operation in one transaction.
4. Core fans out to inboxes and emails, checking access again.
A failure retries with backoff up to 5 attempts, then the task is marked `failed` with its error, visible with the other queue tasks. A rule or content type that is no longer registered is skipped with a warning in the logs, never retried forever. Nothing depends on a long-running process. Any request or the cron endpoint drives the queue.
## Cleanup [#cleanup]
Deleting a record stores a cleanup intent in the same transaction. Once it runs, the record's notifications leave every inbox, and so do notifications about records in its thread when the record was the root, including replies a database cascade removed. A grouped item loses only the deleted contributions and points at the newest one left; it disappears when none is left. Pending emails for those notifications are dropped.
A submission that stops waiting, because a moderator decided it, the author replaced it with a newer proposal or the record was deleted, stores a cleanup intent in the same transaction, and its `approvalPending` notifications leave the moderators' inboxes. Delivery that has not reached an inbox yet is stopped by the access check; in the rare case that delivery and cleanup cross, the item stays behind as "no longer available".
Hiding is not deleting. A hidden record's notifications are only unavailable until it is shown again. A delete that races with a notification being sent is safe either way, because the access check runs again at every step.
## `useRevealHashTarget()` [#userevealhashtarget]
```ts
import { useRevealHashTarget } from "@vitnode/core/hooks/use-reveal-hash-target";
```
Brings the element named by the URL hash into view in a paginated list. Until the element exists it loads the next page; then it scrolls the element to the middle of the screen, keeps it there while late content settles and focuses it (give the element `tabIndex={-1}`).
| Name | Type | Required | Default | Description |
| --------------- | ------------------------ | -------- | ------- | ----------- |
| `prefix` | `string` | Yes | | Only hashes starting with it react, such as `"comment-"` |
| `ready` | `boolean` | Yes | | `false` while the first page is pending |
| `renderedCount` | `number` | Yes | | Items on screen; a change looks again |
| `hasMore` | `boolean` | Yes | | Whether another page exists |
| `isLoadingMore` | `boolean` | Yes | | Whether a page is loading |
| `loadMore` | `() => Promise` | Yes | | Loads the next page |
| `maxLoads` | `number` | No | `10` | Pages to load while looking |
It returns `{ status, targetId }`, where `status` is `"idle"`, `"searching"`, `"found"` or `"missing"`. Show a short notice for `"missing"` so a stale link is not silently ignored.
## Related [#related]
- [Notifications](/docs/content-engine/notifications): set up comment and reply notifications step by step.
- [Limit access](/docs/dev/notifications/access): how core uses `access` and `remove()`.
- [Queue and scale](/docs/dev/notifications/queue-and-scale): how the core workers deliver.
# Notifications (/docs/content-engine/notifications)
When someone answers a comment, its author should hear about it, and when someone comments on an article, the article's author should too. `buildContentNotifications` sets that up for a threaded content type: you name the author fields, the texts and the link, and VitNode sends the notifications through the [core notification system](/docs/dev/notifications), with its bell, inbox, preferences and email.
The server sends them when a comment becomes public, whoever wrote it and however: the shared comment section, your own layout, the public API or the AdminCP. Your React components send nothing, so there is nothing to change in them.
## Before you begin [#before-you-begin]
You need:
- **The newsroom comments**, from [Comments](/docs/content-engine/threads). The comment type has `author: field.user()` and `thread: { parent: "parent", root: "article" }`.
- **[Replies](/docs/content-engine/threads-frontend)**, to have replies to notify about. [Comment actions](/docs/content-engine/threads-editing) is not needed.
- **Two member accounts**, to see a notification arrive. Nobody is notified about their own comment.
## Choose a setup [#choose-a-setup]
| Setup | Who is told | The article needs |
| --- | --- | --- |
| **A: replies only** | The author of the comment being answered | Nothing |
| **B: comments and replies** | Setup A, plus the article's author about every new comment | A to-one, shared `field.user()` author |
Pick A when your articles have no single author, for example when staff write them without one or when the author field lists several people. The Blog plugin is in that case: its articles have `authorId: field.user({ multiple: true })`, so Blog uses setup A. Adding an author field only for notifications is never required.
### Give articles an author (setup B only) [#give-articles-an-author-setup-b-only]
Skip this step for setup A.
The newsroom article already has `author: field.user()` if you followed [Create form](/docs/content-engine/public-write). If you did not, add the field to `src/content/article.ts`. This is an excerpt:
```ts title="plugins/newsroom/src/content/article.ts"
fields: {
title: field.text({ required: true, minLength: 3, maxLength: 200 }),
// ...
author: field.user(), // [!code ++]
},
```
Then build and migrate from the workspace root. The migration adds a nullable `author` column, so existing articles have no author until you set one:
```bash tab="bun"
bun run build:plugins
bun run db:migrate
```
```bash tab="pnpm"
pnpm build:plugins
pnpm db:migrate
```
```bash tab="npm"
npm run build:plugins
npm run db:migrate
```
An article gets its author in one of two ways:
- **In the AdminCP.** Open **AdminCP → Newsroom → Articles** and click **Create Article**, or **Edit** on an existing one. Pick a member in **Author**, then save (**Save changes** when editing). The AdminCP shows a user picker for every `field.user()`, so no member forms are involved.
- **From the site.** With [Create form](/docs/content-engine/public-write), `publicWrite.ownership` sets the member who writes the article as its author.
### Declare the notifications [#declare-the-notifications]
Create `src/api/lib/notifications.ts`. It is server-only, so only `config.api.ts` imports it, never a page.
```ts title="plugins/newsroom/src/api/lib/notifications.ts"
import { buildContentNotifications } from "@vitnode/core/content/server";
import { articleContentType } from "@/content/article";
import { commentContentType } from "@/content/comment";
export const commentNotifications = buildContentNotifications({
content: commentContentType,
root: articleContentType,
rules: {
replies: {
id: "newsroom.comment_reply",
preset: "threadReply",
recipients: { authorField: "author" },
messages: {
label: "newsroom.notifications.comment_reply.label",
description: "newsroom.notifications.comment_reply.description",
comment: "newsroom.notifications.comment_reply.comment",
reply: "newsroom.notifications.comment_reply.reply",
},
target: ({ root, content }) =>
`/news/${root.slug}#comment-${content.id}`,
defaults: { inApp: true, email: "none" },
email: true,
},
},
});
```
```ts title="plugins/newsroom/src/api/lib/notifications.ts"
import { buildContentNotifications } from "@vitnode/core/content/server";
import { articleContentType } from "@/content/article";
import { commentContentType } from "@/content/comment";
export const commentNotifications = buildContentNotifications({
content: commentContentType,
root: articleContentType,
rules: {
replies: {
id: "newsroom.comment_reply",
preset: "threadReply",
recipients: { authorField: "author", rootAuthorField: "author" },
messages: {
label: "newsroom.notifications.comment_reply.label",
description: "newsroom.notifications.comment_reply.description",
comment: "newsroom.notifications.comment_reply.comment",
reply: "newsroom.notifications.comment_reply.reply",
},
target: ({ root, content }) =>
`/news/${root.slug}#comment-${content.id}`,
defaults: { inApp: true, email: "none" },
email: true,
},
},
});
```
- **`id`** is the notification type's id, stored with every notification and every member's preference. Keep it forever, and start it with your plugin's name. The key `replies` is only a name in your code.
- **`preset: "threadReply"`** notifies the author of the comment being answered (`reply` text). With `rootAuthorField`, it also tells the article's author about every new comment (`comment` text). `comment` is required either way; in setup A nobody receives it.
- **`recipients`** names author fields. Both are type-checked. A field that is not a to-one, shared `field.user()` does not compile, which is why a multi-author field cannot be the `rootAuthorField`.
- **`target`** is where the notification leads. `root` is the article and `content` the new comment, both typed.
- **`defaults`** is what members get before they choose: the bell on, email off. `email: true` still lets them turn email on.
### Register it with the plugin [#register-it-with-the-plugin]
Pass the result to `buildApiPlugin` in `src/config.api.ts`, next to the API messages the next step adds:
```ts title="plugins/newsroom/src/config.api.ts"
import { commentNotifications } from "@/api/lib/notifications"; // [!code ++]
import messages from "@/locales/api"; // [!code ++]
export const newsroomApiPlugin = () =>
buildApiPlugin({
manifest,
contentNotifications: [commentNotifications], // [!code ++]
messages, // [!code ++]
modules: [
// ...unchanged
],
});
```
The notification type is registered with the plugin, so it shows up on members' preferences page and on the AdminCP notifications page without more code.
### Add the texts [#add-the-texts]
Notification texts are translated on the API, in the recipient's language, so they live in the plugin's API messages, not in the frontend `locales/en.json`. Create both files:
```json title="plugins/newsroom/src/locales/api/en.json"
{
"newsroom": {
"notifications": {
"comment_reply": {
"label": "Comments and replies",
"description": "Someone comments on your article or replies to your comment.",
"comment": "{actor} commented on \"{title}\"",
"reply": "{actor} replied to your comment on \"{title}\""
}
}
}
}
```
```ts title="plugins/newsroom/src/locales/api/index.ts"
import type { LocaleMessagesMap } from "@vitnode/core/lib/i18n/types";
const messages: LocaleMessagesMap = {
en: async () => await import("./en.json", { with: { type: "json" } }),
};
export default messages;
```
`{actor}` is the comment's author (or "Someone" for a deleted account) and `{title}` the article's `admin.titleField`. Both are plain text, and the inbox never renders them as HTML. For setup A, write the label and description about replies only.
A localized title field is not on the article's own row, so `{title}` would be empty. The Blog plugin's titles are localized, and its texts leave `{title}` out: `"{actor} replied to your comment"`.
### Make the link land on the comment [#make-the-link-land-on-the-comment]
The link ends in `#comment-{id}`, and the shared section from [Comments](/docs/content-engine/threads) gives every comment that element id. When the URL has such a hash, `ContentComments` loads more pages until the comment is on screen, scrolls it into view, focuses it and outlines it. If it is gone or hidden from the reader, the section says **The comment this link points to is no longer available.** There is nothing to add.
A custom layout built on `ContentCommentsRoot` does the same with `useRevealHashTarget` from `@vitnode/core/hooks/use-reveal-hash-target`, as the [Comments API](/docs/content-engine/comments-api#your-own-layout) describes. If your comment type has a permalink route, point `target` there instead. The Blog plugin uses its existing `/blog/comments/:slug` route, which redirects to `#comment-{slug}` under the article in the reader's language, and answers 404 for a comment that is hidden or gone:
```ts title="plugins/blog/src/api/lib/notifications.ts"
target: ({ content }) => `/blog/comments/${encodeURIComponent(content.slug)}`,
```
### Rebuild the plugin [#rebuild-the-plugin]
Run `pnpm build:plugins` from the workspace root, then restart `pnpm dev`. Nothing needs migrating for the notifications themselves, because they use core tables that already exist.
## Who gets notified [#who-gets-notified]
Ada writes the article, Bob and Cleo are members, and Max is a moderator. Recipients are read from the comment, the comment it answers and the article when the notification is sent, never from anyone's session.
| What happens | Setup A | Setup B | Why |
| --- | --- | --- | --- |
| Bob comments on Ada's article | Nobody | Ada (`comment`) | Ada is the article's author |
| Ada comments on her own article | Nobody | Nobody | A comment's author is never notified about it |
| Cleo replies to Bob's comment | Bob (`reply`) | Bob (`reply`), Ada (`comment`) | Bob wrote the parent, Ada the article |
| Ada replies to Bob's comment on her article | Bob (`reply`) | Bob (`reply`) | Ada wrote the reply, so she is left out |
| Cleo replies to Ada's comment on Ada's article | Ada (`reply`) | Ada once (`reply`) | Someone who is both authors gets one notification, worded as a reply |
| Bob replies to his own comment on Ada's article | Nobody | Ada (`comment`) | Bob is left out; Ada still hears about a new comment in her article |
| The article or the parent comment has no author | Nobody for that one | Nobody for that one | An empty author field, including a deleted account, is skipped; the other recipient still gets theirs |
| The new comment has no author | As above | As above | Recipients still get it, and `{actor}` reads "Someone" |
| Max approves Bob's pending comment | As if Bob posted it | As if Bob posted it, minus Max | Bob is the actor shown. Whoever made the comment public is skipped, so Max hears nothing even when he wrote the article or the parent |
Core then drops deleted accounts, members who turned the type off and anyone who may no longer see the comment.
## When it fires [#when-it-fires]
A comment notifies **once, the first time it becomes public**. VitNode tells that moment apart by the comment's `publishedAt`, which is set once and never rewritten. A notification already in an inbox is checked again each time the inbox loads and before each email, so it follows what happens to the comment later.
| What happens to the comment | Notification |
| --- | --- |
| Posted with `create.status: "published"` | Sent a moment later |
| Saved as a draft | Nothing yet. Sent when the draft is first published |
| Waiting for approval, then approved | Sent once, at approval |
| Rejected | None about the comment. A [`moderationDecision` rule](#tell-authors-about-moderation-decisions) can tell its author |
| Edited, or an edit approved | No new one |
| Hidden, then shown again | Shows "This notification is no longer available." while hidden, then comes back. A comment hidden before the notification went out is never announced |
| Unpublished, then published again | Unavailable meanwhile, then back. No new one |
| Deleted without replies | Removed from inboxes |
| Deleted while it has replies | It stays as a placeholder in the thread, and its notification is unavailable. Notifications about its replies stay |
| Its article unpublished, hidden or deleted | Unavailable while the article is not public; removed with a deleted article |
Comments that were already public before you added the rules never notify, so deploying them doesn't bury every author under a year of old news.
The notification is stored in the same database transaction as the comment, and a background task sends it a moment after the response. If the comment's transaction rolls back, nothing is sent. If the task fails, the queue retries it without ever creating a second notification. [Notifications API](/docs/content-engine/notifications-api#delivery-and-retries) has the details.
## Tell authors about moderation decisions [#tell-authors-about-moderation-decisions]
When comments go through [approval](/docs/content-engine/approvals), add a `moderationDecision` rule to tell the person who submitted a comment what a moderator decided. Newsroom comments are never pending, so this example comes from the Forum plugin, whose forums have [publishing policies](/docs/content-engine/container-policies):
```ts title="plugins/forum/src/api/lib/notifications.ts"
decisions: {
id: "forum.comment_decision",
preset: "moderationDecision",
messages: {
label: "@vitnode/forum.notifications.comment_decision.label",
approved: "@vitnode/forum.notifications.comment_decision.approved",
rejected: "@vitnode/forum.notifications.comment_decision.rejected",
},
target: ({ content, decision }) =>
decision.status === "approved"
? commentPermalink(content.slug)
: FORUM_PENDING_HREF,
},
```
Each decision notifies the submitter once, so a resubmitted comment that is rejected again gets a second notification. A rejected comment is a draft that readers cannot open, so `target` sends its author to their pending list instead of an anchor the topic page does not have. The texts receive `{title}`, `{kind}` (`create` or `edit`) and `{reason}`.
## Tell moderators what waits for approval [#tell-moderators-what-waits-for-approval]
The `approvalPending` preset notifies the moderators who could decide a pending comment or edit, and links to it in the Moderator CP. Add it next to the decisions rule:
```ts title="plugins/forum/src/api/lib/notifications.ts"
pending: {
id: "forum.comment_pending",
preset: "approvalPending",
messages: {
label: "@vitnode/forum.notifications.comment_pending.label",
pending: "@vitnode/forum.notifications.comment_pending.pending",
},
},
```
```json title="plugins/forum/src/locales/api/en.json"
"comment_pending": {
"label": "Comments awaiting approval",
"pending": "{kind, select, edit {An edit to a comment is waiting for approval in {container}} other {A new comment is waiting for approval in {container}}}"
}
```
Only moderators whose `can_approve` covers the comment's forum receive it, and it leaves their inboxes once someone decides. [Get notified](/docs/dev/moderation/review-approvals#get-notified) describes it from the moderator's side, and the [Notifications API](/docs/content-engine/notifications-api#approvalpending-preset) lists the options.
## Preferences and email [#preferences-and-email]
Each rule is an ordinary notification type. Members find **Comments and replies** under **Settings → Notifications** and can turn the notification list, push or email on and off for it. Administrators can change the defaults or switch the type off on the [AdminCP notifications page](/docs/dev/notifications/admincp). Email needs an email adapter and `email: true` (or a `defaults.email` other than `"none"`); immediate emails and daily or weekly digests then work like every other type.
## Check the result [#check-the-result]
You need two members, Ada and Grace. For setup B, first make Ada the author of a published article, as in [Give articles an author](#give-articles-an-author-setup-b-only). For setup A, any published article works.
1. Sign in as Grace in another browser and comment on the article. With setup B, Ada's bell shows a new notification within a few seconds:
2. As Ada, open the notification. The article opens with Grace's comment highlighted, even when it is on a later page of comments:
3. As Ada, reply to Grace's comment. Grace gets "replied to your comment" and Ada gets nothing. Open it as Grace, and the reply is highlighted below Grace's comment.
4. As Grace, open **Settings → Notifications**, expand **Comments and replies** and turn **Notification list** off. Have Ada reply again. Nothing new arrives. Turn it back on.
5. As a moderator, hide Grace's comment. Ada's notification now says it is no longer available. Show the comment again and the notification comes back.
6. Delete the article. Both notifications disappear from the inboxes.
## Related [#related]
- [Notifications API](/docs/content-engine/notifications-api): every option, custom rules, access and retries.
- [Notification types](/docs/dev/notifications/notification-types): what a type controls in the core notification system.
- [Approvals](/docs/content-engine/approvals): when comments wait for a moderator.
# Plugin files (/docs/content-engine/plugin-files)
VitNode reads a plugin's content types from several small files instead of one big config. A different part of the app loads each file, so a public page never downloads the AdminCP's forms and a browser never sees your database code. [First content type](/docs/content-engine/create-a-content-type) writes each file step by step; this page is the lookup.
## Files at a glance [#files-at-a-glance]
| File | Export | Read by | Holds |
| --------------------------------------- | ---------------------------------- | ------------------------------------------ | ------------------------------------------------------------------ |
| `src/content/.ts` | Any name | Every file below | The `defineContentType` definition. Safe in the browser |
| `src/database/.ts` | Every table | Drizzle Kit, from `dist/src/database/*.js` | `createContentModel` and the generated tables. Server only |
| `src/api/modules/admin/admin.module.ts` | Any name | `src/config.api.ts` | `buildContentAdminModule` inside a module named `admin` |
| `src/config.api.ts` | The API plugin, `VitNodeApiPlugin` | The API, and the app's typed `fetcher` | The admin module, and `buildContentPublicModule` for public routes |
| `src/admin/nav.tsx` | `adminNav` | The AdminCP layout, on every AdminCP page | `{ definition, icon }` per content type and container collection |
| `src/admin/content.tsx` | `adminContent` | The content screens, loaded on demand | Screen registrations, custom cells, fields and form layouts |
| `src/content.ts` | `contentTypes` | The web build and the API at startup | Every content type with `delivery` or `search` |
| `src/routes.ts` | `routes` | The web build | The pages that serve `delivery` and `search` URLs |
| `src/config.tsx` | The plugin | The app's `vitnode.config.ts` | `manifest`, `messages`, `localeFiles` and `routes` only |
| `src/manifest.gen.ts` | `manifest` | Every file that needs the plugin id | The plugin id as `manifest.id`. Written by `vitnode build` / `dev` |
| `src/api/builders.ts` | `buildModule`, `buildRoute`, `buildContent*Module` | Every API module and route file | The builders bound to `manifest` by `bindApiPlugin` and `bindContentPlugin` |
| `src/locales/en.json` | JSON | The app, through `localeFiles` | Labels for content types, fields and permissions |
A content type with an AdminCP screen needs an entry in both `admin/nav` and `admin/content`. The first adds the sidebar link, the second the screen behind it. They are separate files so the sidebar stays small on every AdminCP page, while form and editor code loads only with the screen.
Without custom cells, fields or layouts, `admin/content` can re-export the nav list, as the newsroom plugin does:
```tsx title="plugins/newsroom/src/admin/content.tsx"
export { adminNav as adminContent } from "./nav";
```
Once you customize a screen, build `adminContent` on its own and reuse the nav entries, as the blog plugin does:
```tsx title="plugins/blog/src/admin/content.tsx (excerpt)"
import type { ContentFrontendPluginSource } from "@vitnode/core/lib/plugin";
import { contentTypeAdmin } from "@vitnode/core/lib/plugin";
import { manifest } from "@/manifest.gen";
import { BlogCategoryColorCell } from "@/views/admin/category/color-cell";
import { BlogCategoryColorField } from "@/views/admin/category/color-field";
import { blogCategoryNav } from "./nav";
export const adminContent = {
pluginId: manifest.id,
contentTypes: [
contentTypeAdmin({
...blogCategoryNav,
fields: {
color: { component: BlogCategoryColorField },
},
columns: {
color: { cell: BlogCategoryColorCell },
},
}),
],
} satisfies ContentFrontendPluginSource;
```
## How the app finds them [#how-the-app-finds-them]
The app never imports these files by hand. Its Vite plugin resolves a fixed subpath of every plugin listed in `vitnode.config.ts` and writes the result into a generated file:
| Subpath | Generated file | Used for |
| -------------------------- | ----------------------------- | ----------------------------------------------------- |
| `/admin/nav` | `src/admin-nav.gen.ts` | The AdminCP sidebar |
| `/admin/content` | `src/content-registry.gen.ts` | The AdminCP content screens |
| `/content` | `src/content-modules.gen.ts` | URL checks in the build and in the API |
| `/config.api` | `src/api-registry.gen.ts` | Types for `fetcher`, imported with `import type` only |
| `/routes` | `src/plugin-routes.gen.ts` | Plugin pages |
This happens each time `vite dev` or `vite build` starts, and the dev server regenerates the files when a resolved module changes. A subpath that does not resolve is skipped without an error, because most plugins have no content types. That is also the usual reason a new screen does not show up: a wrong file path, a wrong export name, or a plugin that was not rebuilt.
Resolution only works when the plugin id equals the npm package name and the package exports its `dist` folder. A generated plugin already has the right `exports`:
```json title="plugins/newsroom/package.json"
{
"name": "newsroom",
"exports": {
"./locales/*.json": "./src/locales/*.json",
"./*": {
"import": "./dist/src/*.js",
"types": "./dist/src/*.d.ts",
"default": "./dist/src/*.js"
}
}
}
```
Tables are the exception. Drizzle Kit reads `node_modules//dist/src/database/*.js` directly for every plugin in the API config. Export each table from those files, or it never reaches a migration. [Migrations](/docs/content-engine/database#export-every-table) shows a model with several tables.
## Keep `config.tsx` small [#keep-configtsx-small]
`config.tsx` is bundled with the document shell of every public page:
```tsx title="plugins/newsroom/src/config.tsx"
import { buildPlugin } from "@vitnode/core/lib/plugin";
import messages from "./locales";
import { manifest } from "./manifest.gen";
import { routes } from "./routes";
export const newsroomPlugin = () =>
buildPlugin({
manifest,
localeFiles: {
en: "newsroom/locales/en.json",
},
messages,
routes,
});
```
Do not import `admin/nav` or `admin/content` here. The app loads `admin/nav` with the AdminCP layout and `admin/content` behind a dynamic `import()`, so form code arrives only with the screen that needs it. Pulling them into `config.tsx` would put the whole editing stack, rich text editor included, into every public page.
`localeFiles` maps each language to your locale JSON so the app can load it. Without it nothing fails, but every label from your locale file is missing.
## `content.ts` and public URLs [#contentts-and-public-urls]
A content type with `delivery` or `search` publishes URLs. List every such content type in `src/content.ts`. The newsroom plugin lists all of its types, which is allowed:
```ts title="plugins/newsroom/src/content.ts"
import { articleContentType } from "@/content/article";
import { bulletinContentType } from "@/content/bulletin";
import { categoryContentType } from "@/content/category";
import { commentContentType } from "@/content/comment";
import { eventContentType } from "@/content/event";
import { explainerContentType } from "@/content/explainer";
import { letterContentType } from "@/content/letter";
import { pageContentType } from "@/content/page";
import { storyContentType } from "@/content/story";
import { tagContentType } from "@/content/tag";
export const contentTypes = [
articleContentType,
categoryContentType,
commentContentType,
storyContentType,
explainerContentType,
bulletinContentType,
tagContentType,
eventContentType,
pageContentType,
letterContentType,
];
```
Keep the module browser-safe. It imports definitions only, never `src/database`. The web build checks that one of your pages serves each URL, and the API refuses to start when a plugin publishes URLs that this module does not declare. See [Content URLs need a page](/docs/dev/i18n/localized-urls-advanced#content-urls-need-a-page).
## Errors [#errors]
| Error or symptom | Cause | Fix |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| A content type has no sidebar entry or screen | `admin/nav` or `admin/content` did not resolve, or the export name is wrong | Check the file path and the `adminNav` / `adminContent` export |
| A table is missing from the migration | The table is not exported from `src/database/*.ts`, or the plugin was not built | Export it and run `db:migrate` while `pnpm dev` runs |
| `content-module-missing` when the API starts | A content type has `delivery` or `search`, but `/content` does not resolve | Add `src/content.ts` with `export const contentTypes` |
| `incomplete-content-types` when the API starts | `src/content.ts` leaves out a content type that publishes URLs, or declares it differently | Export the same definition the API registers in `contentTypes` |
| `content-url-without-page` in `dev` or `build` | No page route serves a `delivery` or `search` URL | Add the page to `src/routes.ts`, or change the URL |
| Labels show raw keys or field names | `localeFiles` is missing from `config.tsx`, or the key path is wrong | Add `localeFiles` and check the `content.` keys |
# Production (/docs/content-engine/production)
A content type that works on your machine needs a few more checks before real editors and visitors use it. Go through this list for every content type you ship.
## Expose only what you mean to [#expose-only-what-you-mean-to]
- [ ] **Review `publicApi.fields`.** It is the allowlist for everything public: the public API, page metadata from `delivery` and the search index. A field not listed there never leaves the server. Keep internal notes, moderation flags and anything personal out of it.
- [ ] **Keep `publication` on.** `publicApi` and `search` both refuse to load without it, and new records start as drafts, so nothing is public until someone publishes it.
- [ ] **Treat search as public.** `search.titleField`, `descriptionField` and `contentFields` must be public fields, and `search.authorField` shows who wrote a record in search results.
The newsroom story lists eight of its own fields plus `publishedAt`. `code`, `views` and `author` stay private, because they are not in the list:
```ts title="plugins/newsroom/src/content/story.ts (excerpt)"
publicApi: {
path: "stories",
fields: [
"title",
"slug",
"excerpt",
"featured",
"category",
"animation",
"gallery",
"noIndex",
"publishedAt",
],
// ...
},
```
## Grant the right permissions [#grant-the-right-permissions]
- [ ] **Give staff only what they need** in **AdminCP → Staff**. Each content type gets `can_view`, `can_create`, `can_edit` and `can_delete`, plus `can_publish` with `publication`, `can_restore` with `editorial` and `can_hide` with [`visibility`](/docs/content-engine/content-visibility).
- [ ] **Guard your own admin routes.** Generated routes check their permissions themselves. A custom route next to them needs its own `adminStaffPermission`, as shown in [Services](/docs/content-engine/services#save-like-the-admincp).
## Ship the migration [#ship-the-migration]
- [ ] Commit the migration that `pnpm db:migrate` generated together with the content type.
- [ ] Run `db:migrate` as a deploy step. Production never migrates on startup.
- [ ] Read the generated SQL when you change an existing content type. See [Migrations](/docs/content-engine/database).
## Configure what editorial features rely on [#configure-what-editorial-features-rely-on]
- [ ] **Scheduled publishing** is a queue task, and the `process-queue` [cron job](/docs/dev/cron) drains the queue every minute. Make sure something calls your cron endpoint in production.
- [ ] **Set `CRON_SECRET`** to your own random value. The API rejects the built-in default outside development, which stops cron runs and front-end revalidation calls.
- [ ] **Preview links** are built from `VITNODE_WEB_URL` and `VITNODE_API_URL`, which default to localhost. Set both to your public URLs. If either is not a valid absolute URL, the API logs a warning at startup and previews stay off.
- [ ] **Integrations send the version they read.** With `editorial`, a save with an outdated `expectedVersion` fails with `409 CONTENT_VERSION_CONFLICT` instead of overwriting someone else's work.
- [ ] **A separate front end that caches public reads** is listed in `content.revalidateOrigins` with an `https` URL. See [Caching](/docs/content-engine/caching).
- [ ] **Live editing** has its own deployment requirements, listed in the [Live editing API](/docs/content-engine/live-editing-api).
## Check content health [#check-content-health]
**Debug Panel → Search** in the AdminCP (`/admin/core/debug/search`) shows how much of each content type is in the search index. Use **Reindex** on a collection, or **Rebuild index**, after a bulk import or a failed sync.
For a monitoring probe, core has a staff-only route that reports every content type, its search drift per language and failed scheduled effects. It needs the `can_view` permission of the `system` module:
```bash
curl -b "vitnode_auth_admin=" \
http://localhost:8000/api/@vitnode/core/admin/debug/content/status
```
```json
{
"healthy": false,
"searchHealthy": false,
"effectsHealthy": true,
"contentTypes": [
{
"contentTypeId": "newsroom.story",
"pluginId": "newsroom",
"features": {
"editorial": true,
"localization": false,
"publicApi": true,
"publication": true,
"scheduling": true,
"search": true
},
"search": {
"healthy": false,
"expectedTotal": 1,
"canonicalIndexedTotal": 2,
"provider": {
"name": "postgres",
"healthy": false,
"indexedTotal": 2,
"verified": true
}
},
"schedules": { "pending": 0, "withErrors": 0, "failedEffects": 0 }
}
]
}
```
This excerpt shows two indexed documents for one published story, so search is not healthy until you reindex the collection. `failedEffects` counts scheduled publishes that committed but whose event or search update failed. In your own code, `contentEngineDiagnostics(c)` from `@vitnode/core/content/server` returns the same object.
## Know the limits [#know-the-limits]
- Content types are defined in code and shipped with migrations. There is no AdminCP screen for creating them at runtime.
- A relation points at one content type. To link to several unrelated types, use one relation field per type.
- `field.blocks()` is not in the generated form by default. Editors change it through [widgets](/docs/dev/widgets) or a custom field component.
# Public API (/docs/content-engine/public-api)
`publicApi` gives a content type read-only routes anyone can call: a list and a single record. They return only published records, and only the fields you name. Your pages read these routes; nothing about a content type is public until you add them.
This continues the article from [Drafts & publishing](/docs/content-engine/publication): one published article, `Welcome to the newsroom`, and one draft, `Release notes for October`.
### Choose the public fields [#choose-the-public-fields]
Edit `src/content/article.ts` and add `publicApi` after `publication`:
```ts title="plugins/newsroom/src/content/article.ts"
publication: true,
// [!code ++:4]
publicApi: {
path: "news",
fields: ["id", "title", "slug", "body", "publishedAt"],
},
```
- `path` becomes part of the URL, `/api/newsroom/content/news`, and the module name your pages use, `content/news`. Pick one no other plugin in the app uses, because [content pages](/docs/content-engine/public-pages) turn it into a site-wide URL.
- `fields` has no wildcard. A field you add later stays private until you list it here.
- Exactly one slug field must be listed, because the single-record route finds records by it.
### Register the public routes [#register-the-public-routes]
Edit `src/config.api.ts` and add the model to `buildContentPublicModule`. This is an excerpt:
```ts title="plugins/newsroom/src/config.api.ts"
import { buildContentPublicModule } from "@/api/builders"; // [!code ++]
import { articleContent } from "@/database/articles"; // [!code ++]
import { manifest } from "@/manifest.gen";
import { adminModule } from "./api/modules/admin/admin.module";
import { helloModule } from "./api/modules/hello/hello.module";
export const newsroomApiPlugin = () =>
buildApiPlugin({
manifest,
modules: [
helloModule,
adminModule,
buildContentPublicModule({ contentTypes: [articleContent] }), // [!code ++]
],
});
```
`publicApi` adds no columns, so there is nothing to migrate. `pnpm dev` serves the routes as soon as it rebuilds.
## Check the result [#check-the-result]
Call the list route while `pnpm dev` runs:
```bash
curl "http://localhost:3000/api/newsroom/content/news"
```
```json title="200"
{
"edges": [
{
"id": 1,
"title": "Welcome to the newsroom",
"slug": "welcome-to-the-newsroom",
"body": {
"type": "doc",
"content": [
{
"type": "paragraph",
"attrs": { "textAlign": null },
"content": [{ "type": "text", "text": "This is our first article. Staff write and edit it in the AdminCP." }]
}
]
},
"publishedAt": "2026-10-23T18:57:51.156Z"
}
],
"pageInfo": {
"totalCount": 1,
"totalPages": 1,
"currentPage": null,
"pageSize": 25,
"count": 1,
"hasNextPage": false,
"hasPreviousPage": false,
"endCursor": "eyJjb2x1bW4iOiJwdWJsaXNoZWRBdCIs...",
"startCursor": "eyJjb2x1bW4iOiJwdWJsaXNoZWRBdCIs..."
}
}
```
Only the published article is in `edges`, with exactly the five listed fields. Now ask for each article by slug:
```bash
curl -i "http://localhost:3000/api/newsroom/content/news/welcome-to-the-newsroom"
curl -i "http://localhost:3000/api/newsroom/content/news/release-notes-for-october"
```
The first answers `200` with the same record. The draft answers `404` with `Article not found.`, the same answer as a slug that never existed, so the API never reveals that a draft exists.
## Read it from a page [#read-it-from-a-page]
Pages call these routes with the [fetcher](/docs/dev/fetcher). The module is `content/` plus `path`; the route, its parameters and its response are typed from your definition:
```ts
import { fetcher } from "@vitnode/core/tanstack/fetcher";
import { manifest } from "@/manifest.gen";
const res = await fetcher({
plugin: manifest.id,
method: "get",
module: "content/news",
path: "/{slug}",
args: { params: { slug: encodeURIComponent(slug) } },
});
```
A field you did not list, or a module that does not exist, is a compile error. The list route also takes `first` (up to 50), `page` or `cursor`, `search`, `orderBy` and `order`; [List API](/docs/content-engine/public-lists-api) has every parameter, and [Search](/docs/content-engine/public-lists#add-search) shows which options turn them on.
Next, show the articles on the site with a [Content list](/docs/content-engine/public-lists).
# List API (/docs/content-engine/public-lists-api)
Every helper on this page is exported from `@vitnode/core/tanstack/content` and is universal unless noted. For a guided setup, follow [Content list](/docs/content-engine/public-lists). Examples use the blog plugin's `/blog` list.
## `defineContentList` [#definecontentlist]
Declares a list's sorts, URL filters and page size, and returns pure helpers for the URL state.
```ts
const blogPostList = defineContentList({
defaultSort: 'newest',
filters: { category: contentListIdFilter },
pageSize: 12,
sorts: {
newest: { order: 'desc', orderBy: 'publishedAt' },
oldest: { order: 'asc', orderBy: 'publishedAt' },
},
})
```
| Name | Type | Required | Default | Description |
| ------------- | ------------------------------------------------------ | -------- | ------- | -------------------------------------------------------------------------------------------------- |
| `sorts` | `Record` | Yes | | Each URL value of `sort`. `orderBy` must be in `publicApi.orderableFields` or be `publishedAt` |
| `defaultSort` | a key of `sorts` | Yes | | The sort a URL without `sort` uses. Never written to the URL |
| `filters` | `Record value \| undefined>` | No | none | URL filters by URL name. A parser returns a string, number or boolean, or `undefined` to ignore it |
| `pageSize` | `number` | No | `12` | Sent as `first`. Clamped to 1-50, the public list route's limit |
`contentListIdFilter` parses a positive integer id, such as `?category=3`.
| Method | Returns | Behavior |
| ---------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `parseSearch(input)` | `ContentListSearch` | The route's `search` validator. Keeps `page` above 1, a trimmed `q` of up to 256 characters, a non-default `sort` and valid filters. Drops everything else |
| `withSearch(current, patch)` | `ContentListSearch` | Applies a change. Changing anything but `page` resets it to the first page. `undefined` clears a value |
| `isFiltered(search)` | `boolean` | `true` when a term, a filter or a non-default sort is set. `page` does not count |
| `apiQuery(search)` | `ContentListApiQuery` | `{ first, order, orderBy, page, search? }` for the list route. Map filters yourself |
| `href(pathname, search)` | `string` | The internal URL of one state, e.g. `/blog?category=3&page=2` |
| `sorts` | `string[]` | Every sort, in declaration order |
| `defaultSort`, `pageSize` | value | The resolved config |
## `contentListQueryOptions` [#contentlistqueryoptions]
TanStack Query options for one page of a list. Use them in a loader with `queryClient.query(...)` and in a component with `useQuery(...)`.
| Name | Type | Required | Default | Description |
| ----------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------------------- |
| `queryKey` | `QueryKey` | Yes | | The prefix every page shares, e.g. `["@vitnode/blog", "posts"]` |
| `locale` | `string` | Yes | | The page's locale. Pass it on to the API as `?locale=` |
| `search` | object | Yes | | The normalized state from `parseSearch`, or a fixed one such as `{}` |
| `fetch` | `({ locale, search }) => Promise` | Yes | | Makes the request. Write the `fetcher` call here so its route stays typed |
| `staleTime` | `number` | No | `60_000` | Milliseconds a page stays fresh, `RECORD_STALE_TIME` |
The key is `[...queryKey, { locale, ...search }]`. Add `meta: LOADER_DATA_QUERY_META` when a route returns the data from its loader, so it is not sent to the browser twice.
## `contentListPageHead` [#contentlistpagehead]
Builds a plugin route `head` for a list page.
| Name | Type | Required | Default | Description |
| ------------- | ------------------- | -------- | ----------------------- | -------------------------------------- |
| `pathname` | `string` | Yes | | The list's internal path, e.g. `/blog` |
| `search` | object | Yes | | The normalized state |
| `title` | `string` | No | | The page title, already translated |
| `description` | `string` | No | | The meta description |
| `locales` | `readonly string[]` | No | every configured locale | The locales the page exists in |
With an empty `search`, the head is `index, follow` with a canonical link and one `hreflang` alternate per locale. Any other state is `noindex, follow` without a canonical.
## `ContentListResults` [#contentlistresults]
Renders one of the list's states. A React component; item rendering and every label come from you.
| Prop | Type | Required | Default | Description |
| ---------------------------------------- | ---------------------------- | -------- | ------- | ------------------------------------------------ |
| `items` | `TItem[] \| undefined` | Yes | | `undefined` while the first page loads |
| `renderItem` | `(item, index) => ReactNode` | Yes | | One item, inside an `
` |
| `getKey` | `(item) => Key` | Yes | | The React key |
| `label` | `string` | Yes | | The list's accessible name |
| `isFiltered` | `boolean` | Yes | | Picks `noResults` over `empty` for an empty page |
| `loading`, `error`, `empty`, `noResults` | `ReactNode` | Yes | | What each state shows |
| `isError` | `boolean` | No | `false` | Shows `error` while there are no items |
| `isFetching` | `boolean` | No | `false` | Marks the list `aria-busy` and dims it |
| `as` | `"ul" \| "ol"` | No | `"ul"` | The list element |
| `className`, `itemClassName` | `string` | No | | Classes for the list and each `
` |
## `ContentListPagination` [#contentlistpagination]
Numbered page links from the list route's `pageInfo`. Renders nothing for a single page. Links go through `HrefLink`, so the locale prefix is added and every page works without JavaScript.
| Prop | Type | Required | Default | Description |
| ------------ | -------------------------- | -------- | ------------ | ----------------------------------------------- |
| `pageInfo` | `ContentListPageInfo` | Yes | | The list response's `pageInfo` |
| `hrefFor` | `(page: number) => string` | Yes | | A page's internal URL, usually `list.href(...)` |
| `label` | `string` | No | "Pagination" | The `
}
noResults={null}
renderItem={article => (
{article.title}
)}
/>
);
};
```
- **`articlesQueryOptions({ locale, search: {} })`** is the plain list, the first page of `/news` with the ten newest articles. The box shares that request and its cache entry with the list page.
- **Five of ten.** The box drops the article being read and keeps five, so it stays full while the list has at least six articles.
- **`ContentListResults`** picks the state: `loading` until the first answer, `error` when it failed, `empty` when nothing else is published. `isFiltered` is `false` because the box never filters, so `noResults` never shows. The skeleton is hidden from screen readers, which hear the `role="status"` label instead.
### Render it under the article [#render-it-under-the-article]
Edit `src/pages/article-page.tsx`. Import the box and render it after the ``, in a wrapper that keeps the page's width. This is an excerpt:
```tsx title="plugins/newsroom/src/pages/article-page.tsx"
import { LatestArticles } from "./latest-articles"; // [!code ++]
const ArticlePage = ({
loaderData: { item },
}: PluginRoutePageProps) => (
{/* the header and RichTextContent, as before */}
{/* [!code ++] */}
);
```
The container classes move from `` to the wrapper. The box sits outside `` because it is not part of the article.
### Warm the query on the server [#warm-the-query-on-the-server]
`useQuery` does not fetch during server rendering, so on its own the box arrives as a skeleton and loads in the browser. To send it with the HTML, warm the same options in the page's loader. That needs the query client, which `defineRoute` from `@vitnode/core/tanstack/plugin-routes` passes to `load`. Replace the route in `src/pages/article-page.tsx`; this is an excerpt:
```tsx title="plugins/newsroom/src/pages/article-page.tsx"
import type { PluginRoutePageProps } from "@vitnode/core/routing"; // [!code highlight]
import { defineRoute } from "@vitnode/core/tanstack/plugin-routes"; // [!code ++]
import { articlesQueryOptions } from "./article-list"; // [!code ++]
export const route = defineRoute({
load: async ({ context, params }) => {
const page = await loadArticle(params.slug);
// A failure leaves the box to retry in the browser instead of
// breaking the article.
await context.queryClient
.query(articlesQueryOptions({ locale: context.locale, search: {} }))
.catch(() => null);
return page;
},
head: ({ loaderData }) =>
contentDeliveryPageHead(loaderData?.metadata, {
title: loaderData?.item.title,
}),
});
```
`definePluginRoute` is no longer imported from `@vitnode/core/routing`; only the `PluginRoutePageProps` type is. The `/news` loader passes `LOADER_DATA_QUERY_META`, which keeps its query out of the HTML because the page reads it from loader data. This loader leaves it out on purpose. The server sends the query with the page, so `useQuery` finds it in the browser without a request. Both build the same query key, so moving from `/news` to an article reuses the cached list too.
### Add the labels [#add-the-labels]
Add a `latest` group under `newsroom.articles` in `src/locales/en.json`. The article page already loads the `newsroom.articles` messages:
```json title="plugins/newsroom/src/locales/en.json"
{
"newsroom": {
"articles": {
"latest": {
"title": "Latest articles",
"all": "All news",
"empty": "No other articles yet.",
"error": "The latest articles could not be loaded.",
"loading": "Loading the latest articles"
}
}
}
}
```
## Check the result [#check-the-result]
Open `http://localhost:3000/news/welcome-to-the-newsroom`. Below the article, **Latest articles** lists the five newest other articles, with **All news** linking to `/news`:
- **View the page source.** The five titles are in the HTML, so the box needs no request after the page loads.
- **Open another article.** The box leaves that article out and shows the next one instead.
- **Publish an article in the AdminCP** and reload an article page. The new article tops the box. Pages that write articles, such as the [Create form](/docs/content-engine/public-write-frontend), invalidate `[manifest.id, "articles"]`, which refreshes the box together with `/news`.
## Use a different list shape [#use-a-different-list-shape]
Reusing the first page of `/news` keeps one request and one cache entry, but it also means the box follows that list's sort and size. For a box that needs its own page size, sort or filter, such as the three newest articles in one category, declare a second list with [`defineContentList`](/docs/content-engine/public-lists-api#definecontentlist) and its own query options. Keep the `queryKey` prefix `[manifest.id, "articles"]`, so one invalidation still refreshes both.
Next, let members write articles too with [Member writing](/docs/content-engine/public-write). To let readers flag an article first, [Reports](/docs/content-engine/reports) works from here as well.
# Content list (/docs/content-engine/public-lists)
A content list is a page such as `/news` that shows published records a page at a time. The Content Engine provides the data, the paging and the list states; your plugin owns the route, the row layout and the words. This tutorial builds `/news` with article titles, links and page numbers, then adds search and sorting.
This continues the article from [Public API](/docs/content-engine/public-api), whose public routes live at `/api/newsroom/content/news`. Publish a few more articles in the AdminCP first, so there is more than one page; this tutorial shows 10 a page.
### Declare the list [#declare-the-list]
Create `src/pages/article-list.ts`. `defineContentList` names the sorts and the page size once. `contentListQueryOptions` turns one URL state into [TanStack Query](/docs/dev/cache) options; write the `fetcher` call inline in `fetch`, so the route and its response stay typed:
```ts title="plugins/newsroom/src/pages/article-list.ts"
import type { ContentListSearch } from "@vitnode/core/tanstack/content";
import {
contentListQueryOptions,
defineContentList,
} from "@vitnode/core/tanstack/content";
import { fetcher } from "@vitnode/core/tanstack/fetcher";
import { manifest } from "@/manifest.gen";
/** `/news`: published articles, newest first, 10 a page. */
export const articleList = defineContentList({
defaultSort: "newest",
pageSize: 10,
sorts: {
newest: { order: "desc", orderBy: "publishedAt" },
},
});
export type ArticleListSearch = ContentListSearch<
(typeof articleList.sorts)[number]
>;
export const articlesQueryOptions = (request: {
locale: string;
search: ArticleListSearch;
}) =>
contentListQueryOptions({
...request,
queryKey: [manifest.id, "articles"],
fetch: async ({ search }) => {
const res = await fetcher({
plugin: manifest.id,
method: "get",
module: "content/news",
path: "/",
args: { query: articleList.apiQuery(search) },
});
if (res.status !== 200) {
throw new Error(`Loading articles answered ${res.status}.`);
}
return await res.json();
},
});
```
- `sorts` maps a URL value to the API's `orderBy` and `order`. `publishedAt` is always orderable.
- `ArticleListSearch` is the list's state as the URL holds it: `page`, and later `q` and `sort`.
- `apiQuery(search)` builds `first`, `page`, `orderBy` and `order` for the list route.
### Add the route [#add-the-route]
Edit `src/routes.ts` and add the page. This is an excerpt:
```ts title="plugins/newsroom/src/routes.ts"
import { articleList } from "./pages/article-list"; // [!code ++]
export const routes = definePluginRoutes([
// [!code ++:5]
page("/news", {
component: lazy(() => import("./pages/articles-page")),
messages: ["newsroom.articles"],
search: articleList.parseSearch,
}),
]);
```
`search` cleans the query string before the loader sees it, so `/news?page=2` becomes `{ page: 2 }` and `/news?page=1` the same state as `/news`. `messages` loads the `newsroom.articles` translations for the page and its head.
### Write the page [#write-the-page]
Create `src/pages/articles-page.tsx`. This is the complete file:
```tsx title="plugins/newsroom/src/pages/articles-page.tsx"
import type { PluginRoutePageProps } from "@vitnode/core/routing";
import { DateFormat } from "@vitnode/core/components/date-format";
import { LOADER_DATA_QUERY_META } from "@vitnode/core/lib/query-client";
import {
contentListPageHead,
ContentListPagination,
ContentListResults,
} from "@vitnode/core/tanstack/content";
import { HrefLink } from "@vitnode/core/tanstack/link";
import {
defineRoute,
type RouteLoadContext,
} from "@vitnode/core/tanstack/plugin-routes";
import { useTranslations } from "use-intl";
import type { ArticleListSearch } from "./article-list";
import { articleList, articlesQueryOptions } from "./article-list";
const loadArticles = async (
{ locale, queryClient }: RouteLoadContext,
search: ArticleListSearch,
) =>
// A failed list becomes a message on the page, not an error page.
await queryClient
.query({
...articlesQueryOptions({ locale, search }),
meta: LOADER_DATA_QUERY_META,
})
.catch(() => null);
type ArticlesPageData = Awaited>;
export const route = defineRoute({
load: async ({ context, search }) => await loadArticles(context, search),
head: ({ search, t }) =>
contentListPageHead({
description: t("newsroom.articles.desc"),
pathname: "/news",
search,
title: t("newsroom.articles.title"),
}),
});
const ArticlesPage = ({
loaderData: articles,
search,
}: PluginRoutePageProps) => {
const t = useTranslations("newsroom.articles");
return (
);
};
export default ArticlesPage;
```
- **The loader** runs on the server for the first visit and in the browser on later navigations. It warms the query with `queryClient.query`, so the page is in the server-rendered HTML. `LOADER_DATA_QUERY_META` keeps the query out of the HTML's cache payload, because the router already sends the loader data.
- **A failed request** becomes `null`, and `ContentListResults` shows `error` instead of breaking the page. It also decides between `empty` (nothing published) and `noResults` (nothing matches a search).
- **`ContentListPagination`** renders real links built by `articleList.href`, so paging works before hydration and crawlers can follow it. It renders nothing when there is one page.
- **`contentListPageHead`** sets the title and description. The plain list is indexable; page 2 and later get `noindex, follow`.
### Add the labels [#add-the-labels]
Add the `articles` keys to `src/locales/en.json`, inside `newsroom`:
```json title="plugins/newsroom/src/locales/en.json"
{
"newsroom": {
"articles": {
"title": "News",
"desc": "The latest articles from our team.",
"empty": "No articles yet. Check back soon.",
"error": "The articles could not be loaded. Try again in a moment.",
"pagination": "Article pages"
}
}
}
```
## Check the result [#check-the-result]
Open `http://localhost:3000/news`:
1. The newest ten published articles show, newest first. `Release notes for October` is a draft, so it never appears.
2. Click **2**. The URL becomes `/news?page=2` and the remaining articles show.
3. Titles link to `/news/{slug}`. The next tutorial, [Content page](/docs/content-engine/public-pages), creates that page.
## Add search [#add-search]
Searching narrows the list on the server. Add `searchableFields` to `publicApi` in `src/content/article.ts`:
```ts title="plugins/newsroom/src/content/article.ts"
publicApi: {
path: "news",
fields: ["id", "title", "slug", "body", "publishedAt"],
searchableFields: ["title"], // [!code ++]
},
```
Then add a search field to the page, in three places in `src/pages/articles-page.tsx`. First, the imports:
```tsx title="plugins/newsroom/src/pages/articles-page.tsx"
import { Input } from "@vitnode/core/components/ui/input";
import {
contentListPageHead,
ContentListPagination,
ContentListResults,
useContentListSearchInput, // [!code ++]
} from "@vitnode/core/tanstack/content";
import { useTransition } from "react";
```
Second, the search state at the top of `ArticlesPage`, which now also reads `navigate` from its props:
```tsx title="plugins/newsroom/src/pages/articles-page.tsx"
const ArticlesPage = ({
loaderData: articles,
navigate, // [!code ++]
search,
}: PluginRoutePageProps) => {
const t = useTranslations("newsroom.articles");
// [!code ++:15]
const [isPending, startTransition] = useTransition();
const update = (patch: Partial) => {
startTransition(async () => {
await navigate({
resetScroll: false,
search: articleList.withSearch(search, patch),
});
});
};
const input = useContentListSearchInput({
onCommit: q => {
update({ q });
},
value: search.q,
});
```
Third, the field below the `
`, and two props on `ContentListResults`:
```tsx title="plugins/newsroom/src/pages/articles-page.tsx"
{t("no_results")}} // [!code highlight]
// ...the other props stay as they are
/>
```
- `useContentListSearchInput` waits until typing pauses, then calls `onCommit`. Enter commits at once.
- `withSearch` writes `?q=` and goes back to page 1, because page 4 of the old results says nothing about the new ones.
- `isFetching` keeps the current results on screen, dimmed and marked `aria-busy`, while the next ones load.
Add `"search_label": "Search articles"` and `"no_results": "No articles match your search."` to the `articles` labels.
## Add sorting [#add-sorting]
Add `orderableFields: ["title"]` to `publicApi`, then more sorts to `articleList`:
```ts title="plugins/newsroom/src/pages/article-list.ts"
sorts: {
newest: { order: "desc", orderBy: "publishedAt" },
oldest: { order: "asc", orderBy: "publishedAt" }, // [!code ++]
title: { order: "asc", orderBy: "title" }, // [!code ++]
},
```
Render a select next to the search field, using the same `update` function:
```tsx title="plugins/newsroom/src/pages/articles-page.tsx"
import {
NativeSelect,
NativeSelectOption,
} from "@vitnode/core/components/ui/native-select";
{
update({ sort: articleList.sorts.find(sort => sort === event.target.value) });
}}
value={search.sort ?? articleList.defaultSort}
>
{articleList.sorts.map(sort => (
{t(`sort.${sort}`)}
))}
;
```
Label each sort under `articles.sort`, such as `"sort": { "newest": "Newest first", "oldest": "Oldest first", "title": "Title A–Z" }`, and add `"sort_label": "Sort articles"`. The list never writes the default sort to the URL, so `/news?sort=newest` and `/news` are the same page.
## Keep list rows light [#keep-list-rows-light]
The list returns every field in `fields`, including each article's body. Name the fields a row needs with `listFields`; the single-record route still returns all of `fields`:
```ts title="plugins/newsroom/src/content/article.ts"
publicApi: {
path: "news",
fields: ["id", "title", "slug", "body", "publishedAt"],
listFields: ["id", "title", "slug", "publishedAt"], // [!code ++]
},
```
## Add a filter [#add-a-filter]
A filter needs a field that `publicApi.filterableFields` lists, such as a relation, an enum or a [container](/docs/content-engine/containers). Add a parser for its URL value in `defineContentList({ filters })`, and pass the value to the list route in `fetch`. The newsroom plugin's letters list filters by desk this way in `plugins/newsroom/src/pages/letter-list.ts`; [List API](/docs/content-engine/public-lists-api#definecontentlist) lists the parsers.
## How the list URL behaves [#how-the-list-url-behaves]
- **Normalized URLs.** `parseSearch` drops unknown keys, invalid values, `page=1` and the default sort. `/news?sort=newest&page=1&utm_source=x` and `/news` are the same state, so they share a query key and a canonical link.
- **Locales.** On a [localized](/docs/content-engine/localization) content type, pass `locale` in the query. A record with no translation in that language falls back to the default language when the type uses `fallback: "default"`, and each row says which language it is in under `locale`. An unknown `?locale=` answers `404` rather than an English list.
- **Pagination.** `ContentListPagination` reads `currentPage`, `totalPages`, `hasNextPage` and `hasPreviousPage` from `pageInfo`, and every page is a real link, so it works before hydration. A `page` past the end gets the last page. The list route also accepts `cursor` for "Older" and "Newer" links; [Container pages](/docs/content-engine/container-frontend#add-the-desk-page) uses it.
- **Caching.** The API caches each list read per query and locale, and every publish, edit, unpublish, hide or delete of the content type expires it. TanStack Query keeps its own copy in the browser for `RECORD_STALE_TIME`, which is why a page that writes records invalidates its list.
- **Hidden records.** With [`visibility`](/docs/content-engine/content-visibility#who-can-still-see-it), a signed-in author, editor or moderator also gets the hidden records they may see. Those rows carry `hidden: true`, so mark them, for example with `HiddenIcon` from `@vitnode/core/components/hidden-icon`. That response is `private, no-store` and skips the API cache. A route with a page `cache` serves signed-in visitors the HTML rendered for guests, so refetch the list in the browser under a key that includes the viewer, like the blog's `blogViewerPostsQueryOptions`. For your own counts or queries, combine `contentListHiddenAccess` and `contentPublicListCondition` from `@vitnode/core/content/server`.
Records reach crawlers through their own pages and the [sitemap](/docs/content-engine/seo#sitemap). The sitemap route lists records, not lists, so add the list's own URL, such as `/news`, where your app builds `/sitemap.xml`.
The blog plugin builds `/blog` and `/blog/category/:slug` from the same pieces with only pages and a category, in `plugins/blog/src/pages/blog-list.ts` and `blog-queries.ts`.
Next, give every article its own page with [Content page](/docs/content-engine/public-pages).
# Content page (/docs/content-engine/public-pages)
Delivery gives every published record a page at a stable URL, such as `/news/welcome-to-the-newsroom`. The Content Engine resolves the URL, answers `404` for drafts and unknown slugs, and builds the page's metadata; your plugin owns the page component.
This continues the article from [Content list](/docs/content-engine/public-lists), whose rows already link to `/news/{slug}`.
### Turn on delivery [#turn-on-delivery]
Edit `src/content/article.ts` and add `delivery` after `publicApi`:
```ts title="plugins/newsroom/src/content/article.ts"
publicApi: {
path: "news",
fields: ["id", "title", "slug", "body", "publishedAt"],
},
delivery: true, // [!code ++]
```
`true` uses every default. The page URL is `/{publicApi.path}/:slug`, so articles live at `/news/:slug`. URLs are site-wide, which is why no other plugin's content type may use the same `publicApi.path`. Delivery adds no columns, so there is nothing to migrate.
### Export the plugin's content types [#export-the-plugins-content-types]
Create `src/content.ts`. It lists every content type with public URLs:
```ts title="plugins/newsroom/src/content.ts"
import { articleContentType } from "@/content/article";
export const contentTypes = [articleContentType];
```
VitNode reads this module by its name. It compares these URLs with your plugin's routes, and `dev` and `build` stop with a `content-url-without-page` error while a content URL has no page, so a broken canonical link never ships. [Plugin files](/docs/content-engine/plugin-files) lists every file VitNode reads.
### Claim the URL [#claim-the-url]
Edit `src/routes.ts` and add the page below the list. This is an excerpt:
```ts title="plugins/newsroom/src/routes.ts"
export const routes = definePluginRoutes([
page("/news", {
component: lazy(() => import("./pages/articles-page")),
messages: ["newsroom.articles"],
search: articleList.parseSearch,
}),
// [!code ++:4]
page("/news/:slug", {
component: lazy(() => import("./pages/article-page")),
messages: ["newsroom.articles"],
}),
]);
```
### Write the page [#write-the-page]
Create `src/pages/article-page.tsx`. This is the complete file:
```tsx title="plugins/newsroom/src/pages/article-page.tsx"
import { DateFormat } from "@vitnode/core/components/date-format";
import { RichTextContent } from "@vitnode/core/components/rich-text";
import { zodRichTextDocument } from "@vitnode/core/content";
import {
definePluginRoute,
type PluginRoutePageProps,
} from "@vitnode/core/routing";
import {
contentDeliveryPage,
contentDeliveryPageHead,
} from "@vitnode/core/tanstack/content";
import { fetcher } from "@vitnode/core/tanstack/fetcher";
import { z } from "zod";
import { manifest } from "@/manifest.gen";
const zodArticle = z.object({
body: zodRichTextDocument,
id: z.number(),
publishedAt: z.string().nullable(),
slug: z.string(),
title: z.string(),
});
const loadArticle = async (slug: string) => {
const [resolution, detail] = await Promise.all([
fetcher({
plugin: manifest.id,
method: "get",
module: "content/news",
path: "/delivery/resolve/{slug}",
args: { params: { slug: encodeURIComponent(slug) } },
}),
fetcher({
plugin: manifest.id,
method: "get",
module: "content/news",
path: "/{slug}",
args: { params: { slug: encodeURIComponent(slug) } },
}),
]);
if (resolution.status !== 200) {
throw new Error(
`Resolving the article "${slug}" answered ${resolution.status}.`,
);
}
return contentDeliveryPage({
item: detail.status === 200 ? zodArticle.parse(await detail.json()) : null,
resolution: await resolution.json(),
});
};
type ArticlePageData = Awaited>;
export const route = definePluginRoute({
load: async ({ params }) => await loadArticle(params.slug),
head: ({ loaderData }) =>
contentDeliveryPageHead(loaderData?.metadata, {
title: loaderData?.item.title,
}),
});
const ArticlePage = ({
loaderData: { item },
}: PluginRoutePageProps) => (
{item.title}
{item.publishedAt ? (
) : null}
);
export default ArticlePage;
```
- **The loader** asks two public routes at once. `/delivery/resolve/{slug}` says whether the URL is a record, an old slug to redirect, or nothing; `/{slug}` returns the public fields.
- **`contentDeliveryPage`** returns `{ item, metadata }`. For an unknown slug or a draft it throws the router's not-found, so the app shows its 404 page with a `404` status, and `item` is never `null` in the component.
- **`zodArticle`** checks the response and types `body` as a rich text document. `RichTextContent` renders it as React elements, on the server and in the browser.
- **`contentDeliveryPageHead`** builds the head from `metadata`. The `title` option is the fallback while no SEO field is configured.
`load` comes before `head`, so TypeScript infers `loaderData`.
## Check the result [#check-the-result]
Open `http://localhost:3000/news/welcome-to-the-newsroom`:
- The page title is `Welcome to the newsroom - VitNode`.
- `/news/release-notes-for-october`, the draft, shows the not-found page with status `404`. Publish it in the AdminCP and the same URL works.
- `/news/no-such-article` answers `404` too.
The loader's first request shows what delivery decided:
```bash
curl http://localhost:3000/api/newsroom/content/news/delivery/resolve/welcome-to-the-newsroom
```
```json title="200"
{
"type": "content",
"canonicalPath": "/news/welcome-to-the-newsroom",
"canonicalInternalPath": "/news/welcome-to-the-newsroom",
"itemId": 1,
"seo": { "description": null, "title": null },
"openGraph": null,
"robots": null,
"alternates": [],
"hreflang": { "languages": {} },
"isFallback": false,
"hidden": false,
"locale": null,
"requestedLocale": null
}
```
`seo` is empty because no SEO fields are configured yet.
## Optional next steps [#optional-next-steps]
- **Titles, descriptions and the sitemap.** Set `delivery.seo` and `delivery.sitemap`, as [SEO](/docs/content-engine/seo) shows.
- **Redirects after a slug change.** Add `editorial: true` and `delivery: { redirects: true }`. The old slug is kept in `core_content_slug_history`, and `contentDeliveryPage` turns a visit to it into a `308` redirect to the new URL. While a record is [hidden](/docs/content-engine/content-visibility), its page and old slugs answer `404`.
- **Edit and Report buttons.** [Permissions](/docs/content-engine/public-permissions) and [Reports](/docs/content-engine/reports) add them next to the title.
- **A custom URL.** Set `delivery.path`, such as `"/articles/:slug"`. It needs exactly one `:slug` and cannot start with `/admin` or `/api`.
## Render other fields [#render-other-fields]
The detail route returns each field in `publicApi.fields` in a shape made for rendering. The blog's `plugins/blog/src/pages/post-page.tsx` uses all of them:
| Field kind | What `/{slug}` returns | Render it with |
| -------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Text, textarea, slug | `string` (or `null` when nullable) | Plain JSX. React escapes it |
| [Rich text](/docs/content-engine/rich-text) | A ProseMirror document. Validate it with `zodRichTextDocument` | `RichTextContent` from `@vitnode/core/components/rich-text` |
| Dates such as `publishedAt` | An ISO string, or `null` | `DateFormat` from `@vitnode/core/components/date-format` inside a `