CLI

All commands exposed by the `cms` binary.

The cms binary is installed by @cms/engine. It loads cms.config.ts (or cms.config.tsx) from the current working directory — override with CMS_CONFIG_PATH. Commands fall into four groups: server (run the app), migration (manage the database schema), user (manage admin accounts), and key (manage API keys).

          cms <command> [args]
        

Run cms with no arguments to see grouped help. An unknown command, subcommand or flag, or a flag missing its value, prints the help and exits with code 1.

Server

cms dev

Starts the dev server on a single port (default 4000). Serves the API at /api, the admin UI at /admin with HMR, and proxies between the two so cookies and CORS are not in the way during local work.

cms dev never changes the database schema. It runs the same check as cms start and refuses to boot while a migration is pending, was left half-applied, or was edited after it was applied; it also refuses when migrations/ is empty. After a config change, run cms migration generate <name> --apply (or generate, then apply), so every migration runs on your machine before it reaches production. Once the server is up, cms dev compares the config with the migrations and warns when a change has no migration yet, naming the tables it touches. It checks again whenever a source file or a migration changes, so an edit made while the server runs gets the same warning, and a note once a new migration covers it. The running server keeps the config it started with, so restart it to serve the change. It warns rather than refuses, so the server keeps running while you iterate.

A local database built by an older cms dev (which pushed the schema instead of applying migrations) has the tables but no migration journal. cms dev and apply say so and print the reset: docker compose down -v, docker compose up -d, cms migration apply.

Switching branches follows the same rules as a deploy. Checking out a branch with migrations you haven’t applied: run cms migration apply. Checking out a branch that lacks a migration you already applied (you applied your feature branch’s migration, then switched back to main): apply refuses, because the database is ahead of the code. Recreate the local database (docker compose down -v, docker compose up -d, cms migration apply), or point DATABASE_URL at a separate database per branch.

cms build

Builds the admin SPA to .cms/admin-dist/. The output is the static bundle that cms start serves at /admin.

cms start

Production entry point. Loads the config, connects to the database, and serves the API + the pre-built admin bundle on PORT (default 4000). Never runs migrations — see cms migration apply.

Migrations

The migration system diffs your code-defined schema against the latest snapshot and produces SQL or TypeScript migrations you commit to your repo. Each applied migration is recorded in the _migrations journal table with a SHA-256 checksum.

cms migration generate [name]

Diffs the current config against the schema the existing migrations build. Writes a new migration to migrations/<YYYYMMDDHHMMSS>_<name>/ containing migration.sql and snapshot.json, plus drizzle-kit’s table snapshot at migrations/.drizzle/<YYYYMMDDHHMMSS>_<name>/snapshot.json. Commit all three. Generating only ever adds files, so migrations from different branches merge in git without conflicts; see Migrations from parallel branches.

Output format is always SQL — there is no flag to emit TypeScript. If you need a migration.ts (data backfill, JS-only logic), generate the SQL migration first, then either rename the file and rewrite it as a TS module, or write a separate TS migration by hand. See .ts data migrations below.

Flags:

  • --check — does not write any files. Exits with code 1 if a migration would have been generated, or if merged branches’ migrations conflict. Auto-resolves ambiguous JSONB renames as drop+add (the safe default). Run it in CI as the guard against a config change merged without its migration.
  • --apply — runs cms migration apply right after: the new migration and any pending ones pulled from teammates. Needs DATABASE_URL.
  • --accept-data-loss — required when the generated SQL contains DROP TABLE, DROP COLUMN, or ADD COLUMN NOT NULL without DEFAULT, or a JSONB backfill that discards content (a dropped key, or a removed union variant — see below). Without it, generate refuses and prints the offending statements.

When one table both gains and loses a column in the same diff, drizzle-kit asks whether that’s a rename, and it can only ask in an interactive terminal. Without one (a pipe, CI, an agent’s shell), generate writes nothing and exits with code 1, saying a TTY is needed; re-run it in an interactive shell. --check doesn’t need to ask: it reads the pending prompt as a missing migration.

Migrations from parallel branches

Each migration records which migrations it was generated on top of. When two branches each add a migration and then merge, generate diffs against the schema both of them build together: the schema both branches started from, plus each branch’s changes. The next migration holds only what’s new, and records both branches’ migrations as its parents.

Branches merge per column, index and constraint, so two branches adding different fields to the same entity merge cleanly. Two branches changing the same object can’t both apply, so generate refuses and names the migrations and the object:

  • the same column, index or constraint (even when both made the identical change: the second ADD COLUMN would fail on apply)
  • a table one branch drops and the other changes
  • an index, constraint or foreign key that points at a column or table the other branch removed
  • the same JSON field reshaped on both branches

To resolve it, keep one branch’s migration. Delete the other’s migration folder and its migrations/.drizzle/<name>/ folder, then run cms migration generate again on top. --check fails on a conflict too, so CI catches it on the merge.

Migration order is the timestamp order, and apply runs whatever the database hasn’t applied yet, so a branch’s older migration merged after a newer one still runs.

Projects created before this layout committed one shared journal in migrations/.drizzle/meta/ and a .drizzle-tag file in each migration. The first generate that succeeds (not --check, and not one that refuses) converts them to one snapshot per migration and removes the old files. Existing migration.sql / migration.ts files and folder names don’t change, so applied checksums still match. Commit the conversion with that migration.

Turning a field into a JSON field

Changing a text field into a union, object or json field moves its column to jsonb, and Postgres needs to be told how to convert the existing values. generate writes that conversion:

  • A link union (one with an external variant holding a url text field) turns each value into { "_type": "external", "url": "<old value>" }, in pending drafts too. No data is lost.
  • Any other field keeps the old value as a JSON string. That won’t match the field’s new shape, so generate treats it as destructive and needs --accept-data-loss. Rewrite the values in the migration if editors shouldn’t re-enter them.

Adding a required field to an existing entity

A required field is a NOT NULL column, and Postgres can’t add one to a table that has rows unless it has a value to give them. generate supplies that value as a temporary default, then drops it so the column ends NOT NULL with no default:

          ALTER TABLE "announcement" ADD COLUMN "lines" jsonb DEFAULT '[]'::jsonb NOT NULL;
ALTER TABLE "announcement" ALTER COLUMN "lines" DROP DEFAULT;
        
  • array and richText fill existing rows with [].
  • text, select, number and date fill them with the field’s defaultValue.
  • boolean already defaults to false.

Any other required field — object, union, json, a single relation, a field a unique rule names on its own, a slug, or a scalar without defaultValue — has no value to fill with, so generate refuses it and names the field. --accept-data-loss doesn’t bypass this: the statement would fail on the first existing row regardless. Either add a defaultValue, or add the field as optional, backfill the rows, and make it required in a later migration.

A required multiple relation is the exception: it’s a junction table, not a column, so the migration adds nothing to existing rows and applies cleanly. Those rows keep zero links, and saving one of them fails validation until it has at least the field’s min links (1 by default).

Making an existing field shared

Before a field is shared, each translation holds its own value. Left as is, the first publish in any locale would overwrite the others. So when a field of a translatable entity becomes shared, generate adds SQL that copies the default locale’s values (i18n.defaultLocale) to the other translations. It does what a publish does:

  • A published translation with a pending draft gets the value in that draft only. Any other translation gets it on its row, and in its pending draft if it has one.
  • Relations point at the target’s counterpart in each translation’s locale, or keep the default locale’s target when there’s none. A multiple relation’s links are rewritten directly.
  • No versions are added and updatedAt isn’t touched. Rows that already match aren’t changed, so running it again changes nothing.

This step runs even when nothing else changed, and --check flags it. Making a field no longer shared generates nothing. Two kinds of field can’t be lined up generically: a polymorphic relation, and an object, array, union or richText that holds relations. For those, generate warns and writes an -- Action required comment in place of the SQL, so the values can be lined up by hand before the first publish.

Removing a union variant

Deleting a variant from a union() (a block type retired from a page builder, say) leaves every stored element of that _type orphaned. Nothing looks broken at first — reads aren’t schema-validated — but every write parses the whole document against the entity’s schema, and the discriminated union no longer has a member for that _type, so an editor touching any field of an affected document could never save it again.

generate therefore emits a real backfill: matching elements of an array-of-union are deleted (survivors keep their order), a single union value is nulled, and any pending draft snapshot in _versions gets the same treatment. Plain history versions are left alone — restoring one already schema-validates on its own. Because this discards authored content, it needs --accept-data-loss.

If the variant was actually renamed, answer “yes” at the rename prompt instead: that rewrites _type in place and keeps the data. The prompt only appears when the removed and added variants’ field shapes are similar enough to be a plausible rename; an unpaired removal is treated as a removal with no prompt.

cms migration apply

Applies pending migrations in order. Always operator-driven — never auto-runs on boot.

Each migration runs inside a transaction by default, serialized via a Postgres advisory lock so concurrent invocations from multiple pods don’t race. The journal table _migrations records each applied migration’s name and checksum.

Before applying pending migrations, apply runs a drift check against the schema the applied migrations build (not every migration on disk — that would always flag the tables the pending migration is about to create). Any divergence is printed as a warning and apply still proceeds.

The check is non-blocking on purpose. apply is often the thing that resolves drift — a forward migration written to reconcile a manual change — so refusing to run would block the fix. It earns its keep in three scenarios CI can’t catch:

  • Manual ALTER in production. Hotfix at 3am, no forward migration written. The next deploy’s apply log surfaces the divergence instead of letting it stay invisible until a query fails on a column that isn’t where the code expects.
  • Environment skew. Staging and prod were meant to be identical and aren’t. You see it in the deploy log of whichever environment ran apply.
  • Pre-failure diagnostics. When a pending migration crashes with column "x" already exists or relation "y" does not exist, the drift report printed seconds earlier explains why.

CI’s cms check-drift only sees the database CI builds for itself, so it can’t detect drift that exists in real environments. Use it as the hard gate on intent (snapshot matches code); the apply-time warning observes reality (live DB matches the last thing we told it to be).

cms migration status

Lists all migrations with a ✓ (applied) or ○ (pending) marker. Pending migrations are tagged with their kind (sql / ts) and no-transaction if applicable, so operators can preview what will run.

cms migration check-drift

Introspects the live database and compares it against the schema every migration on disk builds, branches included. Reports unexpected/missing tables and columns. Exits with code 1 if any drift is detected. Catches “someone ran ALTER TABLE by hand in production.”

cms migration resolve <name>

Recovers a migration that a crashed apply left half-recorded. Only a -- migrate:no-transaction migration can end up there: apply records it as started before its body runs, so a crash midway leaves a row with no completion time. Until it’s resolved, apply and cms start refuse to run and name the migration.

Inspect the database first, then pick one:

  • --completed — the migration’s changes are all present. Marks it completed.
  • --retry — they aren’t, or only partly. Clears the record so the next apply runs the migration again; undo any partial change first if re-running it would fail.

A migration that runs in a transaction (the default) never needs this: a crash rolls back its changes and its record together.

Migration files

Each migration lives in its own numbered directory containing exactly one of:

  • migration.sql — pure DDL/DML. The default output of cms migration generate.
  • migration.ts — exports up(db) for data transforms or schema work that needs JavaScript. Both share the same numbering, journal, and checksum semantics.
          migrations/
  .drizzle/                      # drizzle-kit's table snapshot per generated migration
    20260520143025_initial/
      snapshot.json
  20260520143025_initial/        # generated
    migration.sql
    snapshot.json
  20260521091400_backfill_slugs/ # hand-written
    migration.ts
        

A generated migration you rewrote as migration.ts keeps both its snapshot.json and its .drizzle/ folder: they record the schema it builds, and later migrations diff against it.

A migration written by hand from scratch has no snapshot.json and no .drizzle/ folder: it doesn’t change the schema generate diffs against. If one does carry a snapshot.json (copied in by hand), delete it, or generate asks for the drizzle snapshot a generated migration would have.

.ts data migrations

          import { sql } from "drizzle-orm";
import { batched } from "@cms/engine/migrate-helpers";

export const noTransaction = true; // required when using batched

export async function up(db) {
  await batched(db, {
    query: async (d) => {
      const r = await d.execute(sql`
        SELECT id, title FROM posts
        WHERE slug IS NULL
        ORDER BY id LIMIT 500
      `);
      return r.rows;
    },
    apply: async (rows, tx) => {
      for (const row of rows) {
        await tx.execute(sql`
          UPDATE posts SET slug = ${slugify(row.title)} WHERE id = ${row.id}
        `);
      }
    },
  });
}
        

The batched helper commits per batch. Make the WHERE clause idempotent — a crash mid-run resumes naturally on re-apply because already-processed rows no longer match the predicate.

Header directives

Lines like -- migrate:<directive> at the top of a migration.sql file change apply behavior. TS migrations use export const.

-- migrate:no-transaction

Opts out of the per-file transaction wrapper. Required for statements Postgres can’t run inside a tx (CREATE INDEX CONCURRENTLY, VACUUM, REINDEX CONCURRENTLY).

In a TS migration: export const noTransaction = true;.

Trade-off: if the DDL succeeds but the journal write fails, the schema is changed but unrecorded. Use IF NOT EXISTS / IF EXISTS in such migrations so a retry doesn’t fail on the duplicate.

apply enforces this: a no-transaction migration with an unguarded CREATE TABLE, DROP TABLE, CREATE INDEX, DROP INDEX, ADD COLUMN, or DROP COLUMN is refused before execution. Add IF [NOT] EXISTS to clear the check.

-- migrate:lock-timeout <duration>

Overrides the default lock_timeout of 10s. Pass any Postgres duration (30s, 2min) or 0 to disable. The shorter the timeout, the faster a contended DDL fails — preferable to blocking writes indefinitely.

          -- migrate:lock-timeout 30s
ALTER TABLE posts ADD COLUMN category text;
        

CI integration

          # Catches "config changed but migration not committed" at PR time.
- run: pnpm cms migration generate --check

# Optional: catches manual ALTER drift before deploy.
- run: pnpm cms migration check-drift
        

Schema snapshot format

Each migration writes a snapshot.json describing the resolved schema at that point. Snapshots are JSON and human-reviewable. Each field is serialized with its base type, storage strategy, and column/relation metadata:

          {
  "version": 1,
  "entities": [
    {
      "name": "posts",
      "translatable": false,
      "fields": [
        { "name": "title", "type": "text", "base": "text", "storage": "column", "required": true },
        { "name": "author", "type": "relation", "to": "authors", "storage": "relation" }
      ]
    }
  ]
}
        

Safety semantics summary

Concern Where it’s handled
Concurrent applies Postgres advisory lock around the whole apply loop
Partial migration failures Per-migration transaction wrap (opt out with migrate:no-transaction)
Re-apply safety in no-tx migrations apply refuses unguarded CREATE/DROP TABLE, CREATE/DROP INDEX, ADD/DROP COLUMN
Tampered migration files SHA-256 checksum on every applied row; mismatch on re-apply throws
Long-running DDL blocking production Default lock_timeout=10s (override per-file)
Manual ALTER in the live DB Drift check at apply (warn) + cms migration check-drift (CI, hard gate)
Destructive operations cms migration generate refuses without --accept-data-loss
Config out of sync with migrations cms migration generate --check (CI)
Live DB out of sync with migrations cms migration check-drift
Auto-apply on boot Disabled by design — always an operator step

What’s deliberately not supported

  • Down migrations. Reverting via down() gives false confidence and rarely runs cleanly in production. Write a new forward migration that undoes the change instead.
  • Auto-apply on boot. Two pods rolling out simultaneously is a real failure mode; the advisory lock would serialize them, but visibility matters more. Run cms migration apply as a pre-deploy step.
  • Online schema change. For very large tables that can’t tolerate a brief lock, use a tool like pg_repack or gh-ost. Out of scope here.

User management

cms user create and cms key create write to the database, so like cms dev they refuse to run until every migration is applied. In a setup script, run them after cms migration apply.

cms user create <email>

Creates a new user with the configured admin role, or promotes an existing user with that email to admin. Useful for seeding the first operator and onboarding new admins without writing SQL.

          cms user create alice@example.com
        

Requires a role with isAdmin: true to be defined in your config. See Permissions. The user is written straight to the database, without _user hooks; fields added to _user that are required get their defaultValue. The same goes for the admin cms dev and cms start seed into an empty _user table.

API keys

cms key create

Generates a new random API key, inserts it into the database, and prints the raw value. The raw value is only shown once — store it immediately.

          cms key create
cms key create --name "CI read key" --role editor
        

Flags:

  • --name <name> — display name for the key (default: CLI key)
  • --role <role> — role to assign (default: the configured admin role)

cms key create --raw <key>

Upserts a specific raw key value — idempotent. If a key with that hash already exists it is left unchanged; otherwise it is inserted. Useful for scripted local setups and CI where you need a known key value.

The key must start with cms_k_, the prefix that tells an API key apart from a session token; anything else fails. Keys stored before the prefix existed keep working, but can’t be re-upserted: create a cms_k_ key, switch clients to it, then revoke the old one.

          cms key create --raw cms_k_mysecretkey --name "Seed key"
        

Previous

Config