Set up narew.config.ts
Narew reads your existing Drizzle ORM schema and annotates it with presentation metadata: labels, icons, field widgets, and list display. narew.config.ts is the single entry point that the CLI loads to produce that metadata.
Standalone websites welcome
All @narew/* packages are private workspace packages at version 0.0.0. They are not published to a registry, but the website-facing sources (packages/core with cli, drizzle and optional content beside it under packages/) can be copied into an independent pnpm workspace that depends on them with workspace:* — see Package portability.
Tested toolchain: Node 24 (>= 24.11), pnpm 11.23, TypeScript 7, drizzle-orm 0.45.4, and drizzle-kit 0.31.11.
Project dependencies
A typical project package.json pins the first-party packages to the workspace and the verified Drizzle versions:
{
"name": "narew-blog",
"version": "0.0.0",
"private": true,
"type": "module",
"dependencies": {
"@narew/content": "workspace:*",
"@narew/core": "workspace:*",
"@narew/drizzle": "workspace:*",
"drizzle-orm": "0.45.4"
},
"devDependencies": {
"@cloudflare/workers-types": "5.20261006.1",
"@narew/cli": "workspace:*",
"drizzle-kit": "0.31.11",
"typescript": "7.0.2",
"wrangler": "^4.0.0"
}
}Run pnpm install from the workspace root, then run every command below from the project package directory.
Define the schema
Create src/db/schema.ts. The Drizzle ORM schema owns your tables and constraints; Narew never redefines columns, it annotates them.
import { table } from "@narew/drizzle/table";
import { sql } from "drizzle-orm";
import { integer, text } from "drizzle-orm/sqlite-core";
export const authors = table("authors", {
name: text().notNull(),
});
export const posts = table("posts", {
title: text().notNull(),
slug: text().notNull().unique(),
status: text({ enum: ["draft", "published"] })
.notNull()
.default("draft"),
authorId: integer("author_id")
.notNull()
.references(() => authors.id),
views: integer().notNull().default(0),
content: text({ mode: "json" }),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
});table() from @narew/drizzle/table is a thin wrapper over Drizzle's sqliteTable that adds the conventional id column (integer PRIMARY KEY AUTOINCREMENT). It returns a real Drizzle table, so drizzle-kit, relations and website queries behave exactly as usual:
- an explicit
idcolumn in the field map replaces the generated one — for exampleid: text().primaryKey()for UUID or slug keys; { id: "none" }omits it entirely, for junction tables with a composite primary key.
Tables may also be declared directly in narew.config.ts: export them and the default Drizzle configuration reads the schema from that file. A small content-only project then needs one file, not two. Keep the tables in src/db/schema.ts when a website imports the same module, so the site never evaluates the CMS configuration.
A few rules matter to Narew:
- Use database defaults (
.default(...), including SQL defaults like theunixepoch()default above), never$defaultFnor$onUpdateFn. The hosted CMS cannot execute your JavaScript. text({ enum: [...] })gives you an inferred set of values the select widget must cover exactly.- Auto-increment primary keys are read-only automatically; the dashboard never asks editors to type an
id. text({ mode: "json" })columns map to JSON, rich-text, or gallery widgets.
Constrain fields
Field rules are declared in narew.config.ts, inside the field's widget options as a nested rules object — next to label, never in the Drizzle schema:
defineCollection(posts, (field) => ({
label: "Posts",
fields: {
title: field.title.text({
label: "Title",
rules: { minLength: 3, maxLength: 120, notBlank: true },
}),
slug: field.slug.slug({
from: "title",
rules: { characters: "a-z0-9_-", minLength: 1, maxLength: 80 },
}),
views: field.views.number({ label: "Views", rules: { minValue: 0, integer: true } }),
},
}));Text widgets (text, textarea, email, url, slug) accept minLength, maxLength, notBlank, and characters; number accepts minValue, maxValue, and integer. TypeScript only offers the rules that fit the column's type, and Narew rejects wrong combinations at defineConfig time too. Rules stay field metadata, not widget settings: changing text to textarea keeps them.
narew-cms generate writes the rules into field metadata, so the API rejects invalid writes with FIELD_VALIDATION_FAILED and per-field issues, and the dashboard renders the same messages inline. Rules apply to values written through the CMS API and editor; direct SQL writes to D1 are not guarded.
Behavior notes:
- String lengths count Unicode code points, matching SQLite
length(). - Constrained text columns reject embedded NUL characters.
charactersis a safe ASCII whitelist (letters, digits,_,-, space, and ascending ranges likea-z), not a regular expression. Values are never rewritten:notBlankonly checks that the string is non-empty after trimming, it does not trim what gets saved.NULLstill comes from the column itself:.notNull()means the value is mandatory,notBlankmeans a non-empty string after trimming.text({ length })alone still setsmaxLengthmetadata; if a widget also setsmaxLength, the two must agree.- Rules update through
narew-cms generateonly — the application migration stays unchanged because nothing is emitted into the SQL.
Annotate the collections
Create narew.config.ts at the project root. defineCollection(table, (field) => ...) binds presentation to real columns. field.<name> only offers widgets compatible with that column's type, and defineConfig validates the whole project and attaches the serializable metadata object.
import { defineConfig } from "@narew/core";
import { defineCollection } from "@narew/drizzle";
import { authors, posts } from "./src/db/schema.ts";
// Re-exported so `drizzle.config.ts` can read the schema from this one file.
export { authors, posts };
const postCollection = defineCollection(posts, (field) => ({
label: "Posts",
icon: "Article",
website: { path: "/{slug}" },
display: {
title: "title",
subtitle: "slug",
columns: ["title", "status", "authorId", "createdAt"],
defaultSort: { field: "createdAt", direction: "desc" },
},
fields: {
title: field.title.text({
label: "Title",
placeholder: "Post title",
rules: { minLength: 3, maxLength: 120, notBlank: true },
}),
slug: field.slug.slug({
from: "title",
label: "Slug",
rules: { characters: "a-z0-9_-", minLength: 1, maxLength: 80 },
}),
status: field.status.select({ options: { draft: "Draft", published: "Published" } }),
authorId: field.authorId.relation(authors, "name", { label: "Author" }),
views: field.views.number({ label: "Views", rules: { minValue: 0, integer: true } }),
content: field.content.richText({ label: "Content" }),
createdAt: field.createdAt.readonly({ label: "Created at" }),
},
}));
const authorCollection = defineCollection(authors, (field) => ({
label: "Authors",
icon: "Users",
display: { title: "name", columns: ["name"] },
fields: {
name: field.name.text({ label: "Name" }),
},
}));
export default defineConfig({
name: "Narew Blog",
collections: { posts: postCollection, authors: authorCollection },
});The schema import is a plain relative path so the example stays copy-ready with no extra TypeScript configuration. If you prefer the ~/ alias, the CLI always resolves it to the project's src/; TypeScript needs the matching paths mapping ("~/*": ["./src/*"] in tsconfig.json) to agree.
What each annotation does:
display.title/subtitlepick the fields shown as record identity;columnslists table columns;defaultSortorders the list.website.pathis optional. Its root-relative template points to a page, such as/{slug}or/blog/{slug}. Placeholders must name string or number fields, not relations or JSON. The dashboard only offers the website action when the environment has a website URL. It resolves the current editor draft for the preview; a public tab shows saved public content and may return 404. Paths use the website URL's origin, not its path, query, or fragment. Query strings and fragments are not supported in templates.field.slug.slug({ from: "title" })derives the slug editor fromtitle. Uniqueness still comes from the schema's.unique(); the widget alone does not enforce it.field.status.select({ options })labels must cover exactly the ORM enum values (draft,published).field.authorId.relation(authors, "name")points at a registered collection; the ORM foreign key supplies the referenced value field. Both tables must be exported from the same schema module. When the tables live innarew.config.tsitself, that file is the module.field.content.richText()marks a JSON column as structured prose in the metadata; the annotation itself does not guarantee a hosted editor feature.field.createdAt.readonly()keeps server-managed values visible but uneditable.
config.metadata is the validated result. This is what narew-cms generate compiles into a migration. Continue to Drizzle migrations.
Localization and message tables
Narew supports multi-locale content and message dictionaries at the configuration level. Declare supported locales, default locale, and fallback behavior in defineConfig:
import { defineConfig } from "@narew/core";
import { defineCollection, localized, messageTable } from "@narew/drizzle";
import { sqliteTable, text } from "drizzle-orm/sqlite-core";
export const messages = messageTable("app_messages");
export const projectLabels = messageTable("app_labels");
export const posts = sqliteTable("posts", {
id: text().primaryKey(),
title: localized.text("title"),
content: localized.richText("content"),
});
const postCollection = defineCollection(posts, (field) => ({
label: "Posts",
fields: {
title: field.title.text({ label: "Title" }),
content: field.content.richText({ label: "Content" }),
},
}));
export default defineConfig({
name: "Narew Blog",
localization: {
locales: ["en", "pl", "es"],
defaultLocale: "en",
fallback: { es: "en" },
messages: { directory: "./messages", table: messages },
},
projectLabels: { directory: "./labels", table: projectLabels },
collections: { posts: postCollection },
});- Localized columns:
localized.text()andlocalized.richText()from@narew/drizzledeclare JSON columns storing language-keyed mappings ({ [locale: string]: value }). - Message tables:
messageTable("<name>")defines an application-owned SQLite table storing key-value translations (namespace,locale,key,value). - Metadata boundaries: Compiled database metadata (
MetadataSchema) records onlylocalization(locales, defaultLocale, fallback) andmessageTables(SQL table identifiers). Local directories (./messages,./labels) and locale file mappings (such asfiles: { es: "esp.json" }) remain private to the local project and are read bynarew-cms messages <preview|import>without being sent into metadata.
Opt in to a publication guard
Existing projects do not have a publication guard. Saving a record through Narew writes directly to D1 and can immediately change a connected website; content.publish alone does not protect an unconfigured project.
To require that permission for every CMS content write in this database, opt in at the defineConfig level:
export default defineConfig({
name: "Narew Blog",
publication: { mode: "all-content-writes" },
collections: { posts: postCollection, authors: authorCollection },
});Run pnpm exec narew-cms generate, review the resulting custom migration, and apply it through the project's existing Drizzle history. The guard applies to create, update, delete, reordering, pinning, and copies into this database. The destination also requires content.publish for the copy preview. A user without that permission cannot save even an unpublished record; Narew does not yet store separate durable drafts or provide a publication workflow.
This setting applies to all collections in the database, not individual fields. Narew does not infer which values a website considers public. Direct D1 writes, public media access, and CMS operations already accepted before activation remain outside this guard. Website queries must still implement their own publication filtering. Enable it only after reviewing roles and external writers.
The opt-in metadata uses a new optional property in the existing format. Upgrade the CMS API and the project's Narew CLI/core together before applying the migration: older strict metadata readers reject the new property. Normal website reads still query D1 directly. Cross-environment copy requires matching metadata, so enable the same configuration in both databases before copying.
Folders, singletons, and form defaults
defineConfig accepts a folders map that groups collections on the Content page. Members are typed collection keys, each collection belongs to at most one folder, and folders carry no icon — the dashboard always renders a plain folder tile:
export default defineConfig({
name: "Narew Blog",
collections: { posts: postCollection, authors: authorCollection },
folders: {
editorial: { label: "Editorial", collections: ["posts", "authors"] },
},
});defineSingleton(table, (field) => ...) marks a one-record collection with the same options as defineCollection. It requires a supported primary key; the dashboard opens its form directly instead of a list, the first save creates the record (requiring content.create), and later saves update it (requiring content.update). The server enforces the single-record invariant inside the same atomic batch as the write, and rejects singleton deletes and generic endpoint bypasses.
defineSingleton(siteSettings, (field) => ({
label: "Site settings",
icon: "Gear",
defaultValues: {
siteName: "Narew Demo",
maintenanceMode: false,
},
fields: {
siteName: field.siteName.text({
label: "Site name",
rules: { minLength: 2, maxLength: 80, notBlank: true },
}),
maintenanceMode: field.maintenanceMode.boolean({ label: "Maintenance mode" }),
},
}));defaultValues are form-only initial values for new drafts — typed against the table's insert shape and validated like submitted values (codec, enum, nullability, rules, rich-text documents). Timestamp columns accept a Date, normalized to an ISO UTC string. They never become SQL defaults, never fill in missing API values, and never overwrite stored data on update. Read-only, hidden, generated, and binary fields reject defaults.