You're reading docs for Nextly Alpha. APIs may change between releases.

Guides

Production migrations

Ship database schema changes to production safely with the Nextly migration CLI. Forward-only model, GitHub Actions, Vercel build step, and other-platform patterns.

Nextly's schema-evolution model splits responsibilities cleanly between development and production:

  • Local development: next dev + Nextly's HMR pipeline auto-applies schema changes as you edit nextly.config.ts.
  • Production: schema changes are committed as .sql files in your repo. A CI/CD step (or your laptop) runs nextly migrate against the production database before the new app code is deployed.

By default the deployed Next.js app does not touch the schema — you apply migrations in CI/build, before deploy (Patterns 1–3). Two production-grade options make this safe and flexible:

  • A migrate lock guards every nextly migrate, so two runs never apply schema at once. It's a pooler-safe lock row (works through Neon/Supabase PgBouncer) with a TTL, plus a --force-unlock escape hatch.
  • Optional run-on-boot (db.runMigrationsOnBoot, opt-in) applies pending migrations during app startup in production — safe across multiple instances thanks to the lock. See Pattern 4.

This page covers the common deploy patterns. Pick whichever fits your stack.

The CLI commands you'll use

CommandPurpose
nextly migrate:baselineRun once, when a project developed with db:sync starts using migrations. Records the schema the database already has as the starting point. See Graduating from db:sync.
nextly migrate:create [name]After you edit nextly.config.ts, generate a .sql file capturing the change. Commit it to git.
nextly migrate:checkCI gate. Verifies migration file integrity and config drift. Does NOT connect to a database.
nextly migrateApplies pending .sql files to the target database. Run from CI or your laptop.
nextly migrate:statusShows applied / pending / failed / unfinished migrations with their checksums and durations. An unfinished one's last attempt recorded no outcome: the process running it stopped, or is still running. Also names where the registry and the tables disagree.
nextly migrate:resolveRecovery: mark a file applied/rolled-back or clean up a failed attempt without running SQL. See Recovering from a failed migration.
nextly migrate:freshWipes all tables and re-applies every migration. Local-dev only. Confirmation required.
nextly migrate:downRolls back the most-recently-applied migration(s) using their -- DOWN section. CLI-only; never runs on boot. See Rolling back a migration.
nextly upgradeRun after upgrading Nextly, once every instance serves the new release. Brings an existing database up to date in steps: it moves old migration records into nextly_schema_events, hashes passwords stored before this release, and removes passwords kept in version history. Says "Already upgraded. Nothing to do." when no step has work. See Upgrading an existing database.
nextly users:clear-plaintext-passwordsFinds accounts an earlier release left holding a password stored as typed and, with --apply --confirm-default-hasher, clears it and ends their sessions. Previews by default. See Clearing passwords stored as typed.

Global flags inherited from the root nextly command: --config <path> (custom nextly.config.ts path), --cwd <path>, --verbose, -q/--quiet, --non-interactive (never prompt; a command that needs an answer stops and names the flag).

nextly migrate:down reverts a single migration at a time (or the last N via --step). It is a manual, CLI-only tool — it never runs on boot. In production, prefer rolling forward with a new corrective migration, or restore from a backup; rollback restores schema shape, not row data. See Rolling back a migration.

Per-command flags

  • nextly migrate -- --dry-run (list what a run would apply, without executing: each plugin's pending migration modules by plugin:<name>/<module>, then the app's pending files with the SQL each would run, in run order and within --step, with anything a run would refuse; the rows in the way of a column made required are counted only for the first migration a run applies, and a later one says they are counted when the run reaches it, since the migrations before it may fill them), --step <n> (apply only N pending migrations, counting a plugin's migration modules, which run first, together with the app's files; a step never ends inside the files that move a field between translated and shared, and the run says when it goes on through them), --force-unlock (clear a stale migrate lock left by a crashed run, then migrate).
  • nextly migrate:baseline -- --name <name> (the migration's name; defaults to baseline), --force-unlock, --dry-run (name the migration and snapshot it would write, whether it would create the ledger table, and the ledger row it would record, without writing any of them or taking the migrate lock; where a run would refuse, it says why and still exits 0).
  • nextly migrate:create -- [name] positional or --name <name> flag, --blank (empty file for custom SQL), --no-transaction (with --blank, a file whose first line is the no-transaction marker; with --plugin, a module with transaction: false), --non-interactive (a global option every command accepts), --accept-renames, --record-snapshot (a migration that changes nothing, whose snapshot records which fields are translated as the database holds them, for a project whose snapshots predate that record; it reads the database, so run it against one that has applied every migration), --dry-run (print the migration it would write and name it and its snapshot, or with --plugin the module and its barrel, without writing any of them; it still asks about possible renames, whose answers shape the migration, and where a run would refuse, it says why and still exits 0).
  • nextly migrate:status -- --json (machine-readable output for CI scripting), --plugin <name> (list that plugin's migration modules instead of the app's files).
  • nextly migrate:resolve -- exactly one of --applied <file>, --rolled-back <file>, --failed-cleanup <file>, --removed <file> (record an applied migration's file removed on purpose; it stays applied); --file-missing (with --rolled-back, say the file is gone from the folder, so it is not read); --skip-verify (with --applied, skip the live-vs-snapshot check; a file with no snapshot is recorded without it when it is marked -- nextly:no-transaction, or on MySQL when its newest attempt failed or never finished); --dry-run (run the same checks and name the ledger rows it would record, recording none).
  • nextly migrate:fresh -- --accept-data-loss (skip confirmation; -f, --force still works for one release, with a notice, and --yes is refused), --seed (run seeders after migrations), --dry-run (name every table it would drop and each migration it would run again, needing no consent and dropping nothing).
  • nextly migrate:down -- --step <n> (roll back the last N migrations, going on through the files that move a field between translated and shared when the step would end inside them), --allow-data-loss (required when the DOWN drops a table or column), --yes (required in production), --dry-run (show targets + DOWN SQL without executing), --plugin <name> (roll back that plugin's modules instead of the app's files), --force-unlock.
  • nextly upgrade -- --confirm-backed-up (required outside a terminal, when a step has work: your statement that the database is backed up), -f, --force (skip the backup prompt), --target-table-name <name> (use another name for the events table when one of that name already exists), --reconcile-core (see Core schema drift after nextly upgrade), --force-unlock, --dry-run (count each step's pending work, all taken before any step runs, and name what a run would refuse, with no backup question and no lock; with --reconcile-core, name each statement the reconcile would run and each drop it would leave in place).
  • nextly users:clear-plaintext-passwords -- --apply (clear the values and end those accounts' sessions, an access token already issued being refused within about ten seconds; without it the command only counts them), --confirm-default-hasher (required with --apply: your statement that no stored password was written by a custom passwordHasher, now or earlier).

Graduating from db:sync to migrations

nextly db:sync is the development loop: it pushes your config straight at the database, with no migration files in between. Production wants the opposite — reviewable files applied in a known order. Moving from one to the other takes one command.

The problem it solves is that your database already has tables and your migration history has nothing in it. Without a starting point, the first nextly migrate:create compares your config to an empty schema and writes CREATE TABLE for every table that already exists. That file cannot be applied to the database it came from.

Run this once, from a machine that can reach the database you developed against:

nextly migrate:baseline

It records the schema the database already has as the point the history begins, writing two files:

  • migrations/<timestamp>_baseline.sql — the statements that would build that schema from nothing. It is not run against your database; it is recorded as already applied. It exists so a new environment, a CI job, or nextly migrate:fresh can build the same schema from the history alone.
  • migrations/meta/<timestamp>_baseline.snapshot.json — the starting point every later migrate:create measures its diff from.

Commit both. From then on the normal loop applies: edit nextly.config.ts, run nextly migrate:create, and get a file containing only what changed.

Do not keep using db:sync against a database that holds content. It compares your config to the database, and when a column disappears and another appears on the same table it has to guess whether that is a rename. It guesses rename.

On one real database, db:sync proposed 10 rename candidates, including:

seo -> created_by          on dc_comparisons
seo -> first_published_at  on dc_comparisons

Every pair was an embedded field-group column being read as an unrelated system column. Accepting them would have written content into created_by and first_published_at. migrate:create proposed zero renames on the same database, because it diffs against the recorded snapshot rather than guessing from shape.

db:sync is for a development database you are willing to throw away.

# One time, on the existing database
nextly migrate:baseline

# From now on, the ordinary loop
nextly migrate:create add_subtitle
nextly migrate

Two things it deliberately refuses:

  • A project that already has a migration history. Baselining again would give it two starting points, and every later diff would depend on which one was read. It reports the snapshot it found and writes nothing.
  • An empty database. There is nothing to adopt; your first migration is an ordinary nextly migrate:create.

If you reach this the other way round — you ran nextly migrate on a db:sync project and it refused with schema drift where every difference reads + table '...' present in DB — that is this same situation, and the error points here.


Most teams should use this. The migration runs on a CI machine that explicitly has your prod DB credentials; if it fails, the Vercel deploy never happens. Old code keeps serving traffic on the old schema.

# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  migrate-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v3
      - uses: actions/setup-node@v4
        with:
          node-version: 24
          cache: pnpm

      - run: pnpm install --frozen-lockfile

      - name: Verify migration integrity
        run: pnpm exec nextly migrate:check

      - name: Apply pending migrations
        env:
          DATABASE_URL: ${{ secrets.PROD_DATABASE_URL }}
          NEXTLY_APPLIED_BY: github-actions-${{ github.run_id }}
        run: pnpm exec nextly migrate

      - uses: amondnet/vercel-action@v25
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          vercel-args: "--prod"

Order of operations:

  1. CI VM checks out the code.
  2. nextly migrate:check verifies file integrity + no uncommitted schema changes.
  3. nextly migrate applies pending .sql files against the prod DB.
  4. Vercel deploys the new app code.

If step 2 or 3 fails, step 4 doesn't run.

NEXTLY_APPLIED_BY is read by nothing in the current codebase. The nextly_schema_events table has an applied_by column, but the migration runner does not populate it, so setting this variable has no effect today.

Pattern 2: Migration in Vercel's build step (simplest)

The default scaffold ships this build script in package.json:

{
  "scripts": {
    "build": "nextly migrate && next build"
  }
}

Configure DATABASE_URL as a Vercel environment variable (available at build time). Every Vercel deploy applies pending migrations before compiling Next.js.

Trade-offs:

  • Zero CI setup. Push to GitHub, Vercel does everything.
  • Multiple Vercel deploys can race if you push twice in rapid succession (e.g. preview + production, or two PRs merging close together). Nextly's filename UNIQUE constraint catches double-insert; the second build will exit non-zero.
  • The Vercel build machine needs prod DB access from its IP range (check with your DB host).

Pattern 3: Manual deploys (laptop)

Run from your laptop:

DATABASE_URL=$PROD_URL pnpm exec nextly migrate
vercel --prod

For non-Vercel hosts, replace vercel --prod with whatever your deploy command is.

Pattern 4: Run migrations on boot (opt-in)

For long-running servers/containers you can have the app apply pending migrations during startup instead of (or in addition to) a CI step. Opt in via config:

// nextly.config.ts
import { defineConfig } from "nextly/config";

export default defineConfig({
  db: {
    runMigrationsOnBoot: true, // default: false
  },
});
  • Production only (NODE_ENV === "production") — a no-op in development.
  • Pending migrations apply during initialization, under the migrate lock, so multiple instances starting together are safe: one applies while the others wait, then all serve with the schema ready.
  • Failure-safe: a failed boot migration is logged and the app continues (it does not crash the process); resolve with nextly migrate.
  • Tune lock takeover with db.migrateLockTtlSeconds (default 900s).

Serverless caveat. Running migrations on boot adds work to cold starts. On platforms with many short-lived instances (e.g. Vercel), prefer the CI patterns above. Boot-time migrations suit long-running servers/containers.

Environment-specific configurations

If your nextly.config.ts differs by environment (e.g. a plugin enabled only in production), a migration generated in one environment can miss the other's schema. Three ways to handle it:

  1. Edit the generated migration after migrate:create to include the environment-specific changes.
  2. Temporarily enable the production env vars locally when generating, so the migration captures the production shape.
  3. Use separate migration files per environment, applied in the matching environment.

Other platforms

Nextly's CLI is platform-agnostic. The pattern is the same on Railway, Render, Fly.io, or AWS:

  1. Configure your deploy pipeline to run nextly migrate against the production DB.
  2. Ensure that step runs before the new code is promoted.
  3. If the migration fails, the deploy should abort.

Specific examples:

  • Railway: Use deploy.preDeployCommand in railway.json. This runs once before the new revision takes traffic, so it does not race across replicas:
    {
      "deploy": {
        "preDeployCommand": ["nextly migrate"]
      }
    }
    Do NOT put nextly migrate in startCommand. startCommand runs on every container start and would race across replicas, which is precisely the failure mode this guide is designed to avoid.
  • Render: Use a pre-deploy command.
  • Fly.io: Use a release_command in fly.toml. The [deploy] is a TOML section header:
    [deploy]
    release_command = "nextly migrate"
  • AWS (ECS, etc.): Add a one-shot task in your pipeline that runs nextly migrate before updating the service.

What nextly migrate does

  1. Connects to the database via DATABASE_URL.
  2. Reads the nextly_schema_events ledger to see which .sql files have been applied (a file_apply event per file).
  3. Checks the app's history against the folder before it changes anything, core tables included. An applied migration the folder lacks = abort with MIGRATION_MISSING (exit 3): a newer build migrated this database, or a file was removed (see A build older than the database). An unresolved attempt stops it as Recovering from a failed migration says. A hash mismatch on an applied file = abort with MIGRATION_TAMPERED (exit 2). No partial state, nothing else runs. migrate:down, migrate:baseline and nextly upgrade --reconcile-core run the same checks first, with the same exit codes.
  4. Discovers pending .sql files in your migrations/ directory (sorted by filename timestamp).
  5. Applies each pending file in one transaction on one connection (on MySQL each DDL statement still commits as it runs; see database support for MySQL caveats). What a file may contain is below.
  6. Records each applied file in nextly_schema_events as a file_apply event, opened with started_at, filename and sha256 and closed with ended_at and statements_executed.
  7. Names where the registry and the tables disagree, once everything above has run. It changes nothing.
  8. Counts the accounts holding a password stored as typed, and when there are any, names the command that clears them. It changes nothing; see Clearing passwords stored as typed.
Exit codeMeaning
0All pending applied OR no pending
1A migration failed during execution
2MIGRATION_TAMPERED. Abort before running any.
3MIGRATION_MISSING. Abort; file referenced in DB but missing from disk.

A build older than the database

Stop every build released before this check, preview deployments that share production's database included, before the first nextly migrate of this version. From this version on, a build whose migrations folder lacks a migration the database records applied stops with exit code 3 instead of reporting the database up to date, and names each missing migration. Deploy the build that holds the files. If a file was removed on purpose, record that with nextly migrate:resolve --removed <file>: the migration stays applied, later runs go on, and if its file returns it is never run again and is checked against its recorded checksum. migrate:down refuses to roll back such a migration while its file is absent. nextly migrate:status lists it as applied (file removed), as information, where an applied migration whose file is gone with no removal recorded shows as applied (file missing). The --json output carries the same value in status.

Where the registry and the tables disagree

The registry (dynamic_collections, dynamic_singles and the field-group registry) is what a running instance serves from: each row names an entity's table and records its fields. Nothing at start compares it with the database. When nextly migrate finishes, and whenever nextly migrate:status runs, each compares them and names, as a warning:

  • every registry row whose table does not exist;
  • every field a registry row records whose column does not exist on that table, such as a plugin's new field whose column was never added;
  • every collection, single or field group the configuration declares (code-first, plugins, and the Builder manifest) that has no registry row.
collection "forms": field "notifyEmail" has no column "notify_email" in table "dc_forms".
The database has not been migrated for the tables and columns above. Run `nextly migrate:create` for a change that has no migration yet, then `nextly migrate`.

A field that keeps its values somewhere else is not expected on the entity's table: a field group, a many-to-many relationship on a collection or single, a virtual field, and a translatable field of a localized entity, which lives in its _locales table. A row whose table is missing is named once, not once per field.

Both commands only read, and neither changes its exit code for what it names. migrate:status --json carries the same findings under registry: missingTables, missingColumns, unregistered, and unreadable (a registry that could not be read, so it was not compared). registry is null on a database with no registry yet, and when the comparison could not run, with the reason in registryError.

What a migration file may contain

Every migration file, plugin module and -- DOWN section runs as one transaction on one database connection, which the runner opens and commits itself, unless it is marked to run outside one. A few kinds of statement cannot live inside that, and nextly migrate, migrate:down and plugins uninstall refuse the whole file before any of it runs. migrate --dry-run and migrate:down --dry-run report the same refusals without executing anything, and migrate:check warns about them.

StatementWhat happensWhy
BEGIN, START TRANSACTION, COMMIT, END (with any modifiers, such as BEGIN IMMEDIATE or START TRANSACTION READ WRITE)Left out; the rest of the file runs. Refused in a no-transaction fileThe runner's own transaction already brackets the file.
SAVEPOINT, ROLLBACK [WORK | TRANSACTION] TO [SAVEPOINT], RELEASE [SAVEPOINT]Run as written. Refused in a no-transaction fileA savepoint works inside the runner's transaction and undoes at most part of the file. On MySQL a schema statement commits on its own and ends the savepoint with it, so keep savepoints to data statements there.
ROLLBACK [WORK | TRANSACTION], ABORT, COMMIT PREPARED, PREPARE TRANSACTION, XA …File refusedEach one would undo or hand off the runner's transaction, which would then record work that did not happen.
PostgreSQL SET … (except SET LOCAL, SET CONSTRAINTS, SET TRANSACTION), RESET, DISCARDFile refusedA session setting stays on the pooled connection after the migration. Use SET LOCAL, which ends with the transaction.
MySQL SET … (except user variables, SET @name = …), including one inside /*!…*/File refusedThe same: SET FOREIGN_KEY_CHECKS = 0 would stay on a pooled connection and switch checks off for whatever it serves next. Order the statements instead (create a table before the tables that reference it, drop it after them), or drop the foreign key and add it back within the migration.
PostgreSQL VACUUM, CREATE/DROP INDEX CONCURRENTLY, REINDEX … CONCURRENTLY, CREATE/DROP DATABASE, CREATE/DROP TABLESPACE, ALTER SYSTEM, CLUSTER naming no table; SQLite VACUUMFile refused, unless it is marked to run outside a transactionThe database cannot run them inside a transaction. Mark the file (-- nextly:no-transaction as its first line) or the module (transaction: false), and they run.
In a no-transaction file: its own BEGIN, START TRANSACTION, COMMIT, END; SAVEPOINT, ROLLBACK … TO, RELEASE; PostgreSQL SET LOCAL, SET CONSTRAINTS, SET TRANSACTIONRefused in a no-transaction fileEach one needs a transaction, and a no-transaction file has none: each statement commits as it runs. Outside one, PostgreSQL ignores SET LOCAL and refuses a savepoint, SQLite opens a transaction for a BEGIN or a savepoint that nothing ends, and a COMMIT has nothing to commit. Move the statement to a file without the marker, which runs in a transaction.
In a no-transaction file on SQLite: PRAGMA foreign_keys = …, PRAGMA defer_foreign_keys = …Refused in a no-transaction fileThe runner switches foreign-key enforcement off for the file and restores it afterwards; see foreign keys on SQLite. Reading the setting (PRAGMA foreign_keys) is allowed.
SQLite ATTACH, DETACHFile refused, marked or notThey change which databases the process's one connection sees, after the migration too.
MySQL LOCK TABLES, UNLOCK TABLES (and the INSTANCE forms)File refused, marked or notThey commit the migration's transaction implicitly, and the locks stay with the pooled connection.

PostgreSQL's ALTER TYPE … ADD VALUE runs inside the transaction (PostgreSQL 12 and later), but the value it adds cannot be used until the transaction commits, so use it in a later migration file.

The error names the statement and says what to write instead.

Running a file outside a transaction

Some statements cannot run inside a transaction at all. The one you are most likely to need is PostgreSQL's CREATE INDEX CONCURRENTLY, which builds an index on a large table without blocking its writes. To run one, put it in a migration file of its own whose first line is the marker:

-- nextly:no-transaction
-- Migration: index_orders_customer

-- UP
CREATE INDEX CONCURRENTLY IF NOT EXISTS orders_customer_idx ON dc_orders (customer_id);

-- DOWN
DROP INDEX CONCURRENTLY IF EXISTS orders_customer_idx;

nextly migrate:create --blank --no-transaction writes a file you can start from, with the marker as its first line. In any other file the marker goes above its -- Migration: line: only the first line counts. A plugin's migration module says the same with transaction: false on the module; see Plugin schema.

A marked file's UP and DOWN run statement by statement, each committing as it runs. nextly migrate, migrate:down and plugins uninstall print a line naming the file before they run it, and migrate:status shows it as (no transaction).

A marked file has no all-or-nothing guarantee, on any dialect. If a statement fails, the statements before it stay applied and are not undone. The error says which statement failed and how many ran before it, and the ledger records the file as failed. Then either:

  • finish the remaining statements by hand and mark the file applied with nextly migrate:resolve --applied <file>. Do not run it again: that would repeat the statements that already ran.
  • reverse the statements that ran, clear the failed attempt with nextly migrate:resolve --failed-cleanup <file>, and run nextly migrate again.

Keep a marked file to the statements that need it, and write them so they can run again (IF NOT EXISTS, IF EXISTS). A CREATE INDEX CONCURRENTLY that fails can leave an invalid index behind: drop it before you retry.

When every schema statement in a failed marked file ran and a later data statement did not, the database already stands where the file ends. nextly migrate does not take that as the file being applied, which would skip the data change for good: while the file's newest attempt is the failed one, it refuses with NEXTLY_MIGRATION_PARTIALLY_APPLIED (logContext.reason is partially-applied) and names the recovery above.

On MySQL the same holds for a file that runs in a transaction. MySQL commits each schema statement as it runs, together with what the transaction did before it, so a failed attempt can leave the statements before the failure applied even without the marker. While such a file's newest attempt is a failed one, nextly migrate refuses it in the same way rather than recording it applied, and the same recoveries apply: --applied records such a file without comparing the live schema when it has no snapshot, as a --blank file has none. On PostgreSQL and SQLite the failed attempt was undone whole, and nextly migrate runs the file again. None of that attempt ran, so --applied still refuses such a file without a snapshot there (NEXTLY_MIGRATION_SNAPSHOT_MISSING) unless you pass --skip-verify.

The same holds the other way round. When the statement that failed changes the schema and a data statement before it ran, the database still stands where the file starts, but the data change stayed: in a marked file on any dialect, and on MySQL in any file, because MySQL commits what the transaction did before a schema statement runs. Running the file again would repeat that data change, so while its newest attempt is the failed one nextly migrate refuses to run it, with the same error and the same recoveries. This holds for a file with no snapshot too.

A plugin module marked transaction: false is recovered the same way, except the marking: migrate:resolve --applied does not take a module, because nextly migrate records a module together with the tables it owns. Once its statements are finished by hand, run nextly migrate:resolve --failed-cleanup plugin:<name>/<module> and then nextly migrate, which records it applied without running it.

The marker does not lift every refusal. Session settings (SET …), a bare ROLLBACK, MySQL's LOCK TABLES and SQLite's ATTACH/DETACH are refused in a marked file too, because what they leave on the connection outlives the file. A marked file also may not hold what needs a transaction: its own BEGIN, START TRANSACTION, COMMIT or END, a savepoint, or PostgreSQL's SET LOCAL, SET CONSTRAINTS and SET TRANSACTION. The refusal names the statement; move it to a file without the marker. On SQLite a marked file may not write PRAGMA foreign_keys or PRAGMA defer_foreign_keys either.

Marking a generated migration changes its contents, so migrate:check then reports CHECKSUM_MISMATCH for it; put statements that need the marker in a file of their own.

Routine and trigger bodies are one statement. A CREATE TRIGGER … BEGIN … END (SQLite, MySQL), a MySQL CREATE PROCEDURE/FUNCTION/EVENT … BEGIN … END, and a PostgreSQL BEGIN ATOMIC function body reach the database whole, so no DELIMITER line is needed. A PostgreSQL $$ … $$ body is likewise never split. A DROP TABLE inside such a body is judged like any other drop in the file: a body that drops a table another owner holds is refused. A PostgreSQL function or procedure whose body is an ordinary quoted string (AS 'DROP TABLE x') is refused, because the check cannot read a string as code: write the body with $$ … $$.

Foreign keys on SQLite

On SQLite, foreign-key enforcement is off while a file runs, and checked before it commits. The runner sets PRAGMA foreign_keys = OFF before the transaction, runs the file, then runs PRAGMA foreign_key_check; if any row would reference a row that no longer exists, the file is rolled back and refused with NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION (logContext.reason is dangling-reference). The setting is restored afterwards. The same error with reason enforcement-still-on means enforcement could not be switched off, because another transaction was open on the connection when the migration started; nothing was applied — re-run the command once that work has finished (at boot, restart the process). This is SQLite's documented way to rebuild a table (create __new_x, copy the rows, drop x, rename): dropping a parent table this way keeps the rows of tables that reference it, instead of deleting them through ON DELETE CASCADE.

A file marked to run outside a transaction gets the same treatment, except the rollback. Enforcement is switched off before its first statement (and the file is refused with enforcement-still-on if it could not be), PRAGMA foreign_key_check runs after its last statement, and the setting is restored afterwards, whether the file finished or failed. If the check finds a new dangling reference, the file is refused with NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION (reason dangling-reference) and recorded as failed, but its statements stay applied, because each committed as it ran: repair or remove the rows the error names, then mark the file applied with nextly migrate:resolve --applied <file>. Because the runner owns the setting, a marked file may not write PRAGMA foreign_keys or PRAGMA defer_foreign_keys.

Builder entities and production

Everything above describes how columns reach production. Entities created in the Visual Schema Builder carry a second thing: a row in a registry table — dynamic_collections, dynamic_singles, or for Field Groups dynamic_components — holding the label, description and admin display settings. A database that has run nextly migrate:field-groups --apply --backup-confirmed holds the Field Group registry as dynamic_field_groups instead, and the runtime reads whichever of the two the database has. Collections and Singles additionally carry the Versions, Revalidate and Webhooks switches; Field Groups have none of those, and the Field Group registry has no columns for them under either name. The runtime reads its Drizzle table from that row, so the row matters as much as the columns do.

Commit ui-schema.json

The Builder dual-writes every entity it creates or saves into the UI-schema manifest — the file db.uiSchemaFile names, ./ui-schema.json by default — for all three entity kinds. Commit that file with your migrations: it is the input nextly migrate:create reads to know a Builder entity exists, and a Builder change missing from the commit cannot appear in any migration.

Two things to know before relying on it:

  • The Builder's own .sql file is unpaired. Saving a Collection writes a timestamped migration but no meta/*.snapshot.json, and nextly migrate:check reports an unpaired .sql as MISSING_SNAPSHOT. Run nextly migrate:create to regenerate the pair, and commit the .sql and its snapshot together rather than committing the Builder's file as-is.
  • A collection created with a starting field is mirrored without it. The create call writes the manifest entry with an empty field list, so the fields arrive only on the next save. Open the new collection and save it once before generating the migration.

It is input, not a deployment artifact. nextly migrate never reads ui-schema.json; it applies .sql files. An entity's registry row reaches another database only when a migration file carries its upsert, and migrate:create appends that upsert only for entities whose table the migration actually changes. So the manifest gets an entity into the generator's view; a DDL change to that entity is what gets its row into production.

The manifest is written by a development-only route, so it is a dev-time artifact you commit rather than something production generates.

What does not travel

  • A metadata-only edit — a label, a description, or the Versions, Revalidate or Webhooks switch, with no column change for that entity — produces no upsert, because migrate:create writes a file only for DDL and filters metadata upserts to the tables that file touches. With no DDL anywhere in the run it writes nothing at all (No changes detected, exit code 0). The value stays in the manifest until some later migration changes that entity's table and carries the row with it. A cleared description is the exception, because it never travels: the manifest records an empty description as absent, and the upsert leaves a column the manifest does not carry as it was, so the other database keeps the old text through every later migration.
  • Status and Internationalization are not metadata: both change columns. Note that an Internationalization toggle whose column moves are emitted as a companion migration can still leave the localized registry value behind, because the upsert is filtered by the same touched-table set the companion file does not populate. Check the registry row after toggling localization on an existing entity.
  • A deletion leaves the registry row behind. Deleting a Collection in the Builder writes a migration that drops its table. Deleting a Single or a Field Group writes none: the Builder drops the development table and removes the manifest entry, and the next migrate:create finds that table in the previous snapshot but not in the manifest and writes the DROP TABLE. Either way the table goes. Its registry row does not: migrate:create builds registry upserts only for entities still in the manifest, and nothing on the nextly migrate path removes a row. The other environment keeps a row describing a table that no longer exists. There is no supported way to remove it through nextly migrate today, and nextly prune does not apply — it only removes plugin: provenance and always retains Builder entities.

What migrate repairs

After applying files, reconcileMigrationMetadata does two things. It registers entities that an applied migration's snapshot describes but the registry lacks, and it promotes a pending row to applied once no unapplied migration still names that entity and its table exists. Which of those reach a Builder entity is narrower than it sounds:

CaseRepaired by nextly migrate?
A pending row, once every migration naming the entity has run and its table existsYes — promoted to applied
A missing collection or single row from a migrate:create deploymentNo — a migrate:create snapshot records tables, not entities, so registration finds nothing to insert. Only an entity-level snapshot, such as a scaffolded template's, restores a row
A missing field group rowNo — registration covers collections and singles only
An existing row with stale labels, descriptions or fieldsNo — the pass promotes status; it does not refresh content
A metadata-only edit that produced no fileNo — there is no artifact to read
The row of a deleted entityNo — nothing on this path removes a row

So run nextly migrate to settle a pending status, but do not rely on it to recreate a registry row that a Builder deployment is missing.

Moving an entity into code

Declaring an entity in nextly.config.ts versions its settings, but it is a conversion of the whole entity rather than a way to version one switch: defineCollection and defineSingle take a complete definition, fields included.

Remove the entity from the manifest (db.uiSchemaFile) as part of the move. migrate:create tolerates the collision — it warns and lets the code-first definition win. What CI then catches depends on the kind: nextly migrate:check runs validateCrossFile, which compares manifest entries against code-first Collection slugs only. A Collection whose manifest entry stays behind fails there on NEXTLY_SCHEMA_SLUG_COLLISION, so it generates a migration locally and is then rejected by CI. A Single or Field Group left behind passes migrate:check, so nothing reminds you to remove it.

What nextly migrate:check does (CI-friendly, no DB)

Runs five integrity checks; first failure exits non-zero with a specific code. Before the drift check it also warns, without failing, about any statement nextly migrate or migrate:down would refuse (REFUSED_STATEMENT), and names each file marked -- nextly:no-transaction. It does not connect, so it cannot tell a file still pending from one already applied, which never runs again.

CheckWhat it catches
CHECKSUM_MISMATCHA .sql file's content differs from its paired .snapshot.json's recorded hash. Someone edited the file after it was generated.
MISSING_SNAPSHOTA .sql file has no paired .snapshot.json (operator deleted the snapshot or the file was hand-added).
INVALID_SNAPSHOTA .snapshot.json exists but is corrupt, hand-edited, or version-incompatible.
MISSING_MIGRATIONA .snapshot.json has no paired .sql (someone deleted the SQL but kept the snapshot).
SCHEMA_DRIFTYour current nextly.config.ts doesn't match the latest snapshot. You forgot to run migrate:create after editing config.

Run it in your PR CI to catch mistakes before they reach production.

Environment variables

VariableWhere usedPurpose
DATABASE_URLAll commandsTarget database. Required (except SQLite, which falls back to file:./data/nextly.db).
NEXTLY_APPLIED_BYmigrateNo effect today: the column exists on nextly_schema_events but the runner does not write it.
NEXTLY_ACCEPT_DATA_LOSS=1migrate, db:sync, migrate:fresh, prune, webhooks:prune, permissions:cleanup, i18n:restore --purgeAcknowledge destructive changes (drops, type narrowings, deleted rows) without an interactive prompt, as --accept-data-loss does. Required for CI runs of destructive migrations.
NEXTLY_ALLOW_CORE_DESTRUCTIVE=1migrateAllow a destructive change to Nextly's own core tables, which migrate otherwise refuses with NEXTLY_CORE_DESTRUCTIVE_REFUSED. Applies to every operation in the run — see below before setting it.
NEXTLY_DROP_RETIRED_AUTH_TABLES=1migrateDrop the retired accounts, sessions and user_permission_cache tables, when they are present in the shape Nextly created them. A table that only shares the name is left alone, but an Auth.js adapter's table has the same shape as accounts or sessions, so check a table is not another app's before setting it. user_permission_cache held permission answers that are now recomputed from roles, so it is dropped even when it holds rows; the drop is logged. Drop it once every instance runs this release, since an earlier release reads it.
NEXTLY_DROP_NONEMPTY_RETIRED=1migrateWith the flag above, also drop a retired accounts or sessions table that still holds rows. Without it such a table is kept, with a warning, and the rest of the run goes ahead.
NEXTLY_ERASE_RETIRED_AUTH_TABLESRuntimeThe retired tables that are Nextly's, comma-separated (accounts, sessions or accounts,sessions). Deleting a user erases their rows only from a table named here, and only while it has the shape Nextly created. Nextly keeps no record that it created either table, so unset, the rows stay and the startup warning says so.

When migrate refuses a destructive core change

nextly migrate stops rather than run an operation that could lose data from Nextly's own tables, reporting NEXTLY_CORE_DESTRUCTIVE_REFUSED. The refusal names every operation it refused — the list you see is the whole list, not a sample — so you can judge them one at a time.

OperationVerdict
A widening, e.g. varchar(20) → varchar(255)Safe. Nothing that fits today stops fitting
A narrowing, e.g. varchar(255) → varchar(20)Safe only if you have measured the longest stored value and it fits
A dropped column, or any other type changeStop. Work out what happens to the existing values first

Two independent facts make a widening safe: the direction, and knowing what the column holds. A narrowing gives you the first only, so go and look:

SELECT max(length(your_column)) FROM your_table;

Then, and only then:

NEXTLY_ALLOW_CORE_DESTRUCTIVE=1 nextly migrate

The flag disables the refusal for every operation in that run, not just the one you judged safe. Read the whole list before setting it.

Clearing passwords stored as typed

Earlier releases stored some passwords as they were typed instead of hashing them: a password of 32 characters or more that contained a colon, given when an account was created, and any value sent to PATCH /admin/api/users/:id/password. Such a value never let anyone sign in, because sign-in only compares against a hash, but it is a readable password in your database and in every backup of it.

nextly migrate counts these accounts after each run and names the command below. To see how many your database holds, without changing anything:

nextly users:clear-plaintext-passwords

If your app passes, or has ever passed, its own passwordHasher to getNextly, do not clear these accounts. The command reads nextly.config.ts, not your app's code, so it cannot see that hasher, and a hash it wrote in a format the command does not recognise is counted here as plain text. Clearing it locks that person out until they reset their password.

The count never includes a value in a format other password hashers write: an argon2, scrypt or pbkdf2 string in the modular-crypt form their libraries write (such as $argon2id$v=19$m=…,t=…,p=…$salt$hash), or a hex salt and digest joined by a colon. Those are left as they are. A value that only starts with $ is not one of them, and is counted.

Clear them only once the upgraded version serves every instance, with no instance of the old one left running. An old instance can still store a password as typed, and one stored after the command has passed its account stays until the command runs again. If you can't be sure, run it again after the rollout.

To clear them, confirming that no stored password was written by a custom hasher:

nextly users:clear-plaintext-passwords --apply --confirm-default-hasher

Without --confirm-default-hasher, --apply changes nothing and exits with an error.

For each such account it removes the stored value and ends its sessions: none of them can be renewed, and an access token already issued is refused within about ten seconds, as a session's account is checked. It prints only counts, never an address or a value, and a second run finds nothing left to change. Accounts with a proper password, and accounts without one, are left as they are.

Clearing the database does not reach your backups. Any backup taken before the command ran still holds these passwords as typed: purge or expire those backups, or treat them as holding exposed passwords.

What the people affected see: signing in with a password is refused with the same message as a wrong password, as it already was. They set a new password with Forgot password, or an administrator sets one for them.

What you should never do

  • Don't call nextly migrate from your deployed app's runtime. It's a CLI tool, not a runtime API. Nextly enforces this with a lint rule for code in init/, route-handler/, dispatcher/, api/, actions/, direct-api/, routeHandler.ts, and next.ts.
  • Don't edit applied migration files. The hash check catches this and aborts with MIGRATION_TAMPERED. To change something already applied, write a new corrective migration.
  • Concurrent nextly migrate runs are guarded by the migrate lock. A second concurrent run won't apply schema at the same time — it either errors with NEXTLY_MIGRATE_LOCK_BUSY (CLI) or waits (boot run). If a crashed run leaves a stale lock, clear it with nextly migrate --force-unlock. (The lock is a pooler-safe row with a TTL; the filename UNIQUE constraint remains a second line of defense.)

Recovering from a failed migration

nextly migrate is forward-only. When a file partially applies or the live schema drifts, use nextly migrate:resolve to fix the bookkeeping in nextly_schema_events — it never runs migration SQL itself. All three modes are idempotent (re-running a no-op exits 0) and take the same lock as migrate.

If nextly migrate fails partway through:

  1. The failure is recorded as a file_apply event with status='failed' and structured error_json containing the SQL state and message.
  2. Inspect with nextly migrate:status --verbose. The error JSON tells you what broke.
  3. Pick the recovery that matches what actually happened:
    • The file actually applied but wasn't recorded (e.g. the process died after the DDL committed): nextly migrate:resolve --applied <file>. This verifies the live schema matches the file's target snapshot before recording it. Pass --skip-verify only if you have manually confirmed the state.
    • A failed attempt is blocking retries and the .sql needs editing first: nextly migrate:resolve --failed-cleanup <file> flips the stuck attempts (every attempt since the file's last other event that failed, or recorded no outcome because the process running it stopped) to rolled_back; each keeps its start time and its error in the ledger, and a failed one its end time. Edit the file, then run nextly migrate again.
    • A file marked to run outside a transaction stopped part-way: finish its remaining statements by hand and mark it with nextly migrate:resolve --applied <file>, rather than running it again, or reverse the statements that ran, clear the attempt with nextly migrate:resolve --failed-cleanup <file>, and run nextly migrate again. For a plugin module, --failed-cleanup plugin:<name>/<module> followed by nextly migrate records it once its statements are finished.
    • You need to re-run a file that was recorded as applied: nextly migrate:resolve --rolled-back <file> — the next nextly migrate treats it as pending again.
    • A migration whose file is gone stopped part-way (a newer build tried it; nextly migrate exits 3 naming it): reverse what of it ran by hand, then nextly migrate:resolve --rolled-back <file> --file-missing. Without --file-missing, --rolled-back needs the file in the folder.
  4. Otherwise, fix the SQL (revert + regenerate via migrate:create) or the underlying database state, then re-run nextly migrate.

For MySQL specifically, partial state is possible because MySQL DDL auto-commits per statement. Manual cleanup may be needed; see MySQL caveats for the recovery playbook.

A field leaving translation, on MySQL

When a translated field becomes shared, migrate:create writes a <timestamp>_shared_localization_<slug>.sql file that copies the default language's value onto the main table and then drops the field's column from the <table>_locales table. If that file fails on MySQL, nextly migrate refuses to run it again, because the drop may already have committed. The refusal names the file and the columns. To recover, check whether <table>_locales still has the column:

  • The column is gone: the file finished. Mark it applied with nextly migrate:resolve --applied <file>.
  • The column is still there: nothing was dropped. Run nextly migrate:resolve --failed-cleanup <file>, then nextly migrate to run it again.
  • The file moves several fields and only some columns are gone: drop the rest from <table>_locales by hand, then mark it applied.

On PostgreSQL and SQLite the file runs in one transaction, so a failed attempt leaves nothing behind and nextly migrate runs it again.

Upgrading an existing database

nextly upgrade is a list of steps, each of which brings one part of an existing database up to date. It takes the steps in order: it counts what a step would change and, when that is more than nothing, runs it and prints its count, before it looks at the next step. So when a later step stops the upgrade, the earlier ones have already been applied; run it again once the cause is fixed, and it carries on. It asks for a backup before the first step that has work. When no step has anything, it prints Already upgraded. Nothing to do. and asks for nothing. Running it again after it finishes changes nothing.

  • Move the migration records into nextly_schema_events. A database from an early alpha keeps them in nextly_migrations and nextly_migration_journal; the step copies them across and drops the old tables.
  • Hash passwords stored before this release. A password inside a group or repeater that is not yet a hash is stored as a hash of itself, so it keeps working. A value already in a password hasher's format is left alone. The step prints a count for each collection, Single and field group, never a value.
  • Remove passwords kept in version history. A version's snapshot never keeps a password. The step strips any it finds from a snapshot captured by an earlier release, leaving the rest of the version as it was, and prints how many versions of each collection and Single it changed.

nextly migrate prints how many passwords are not yet hashed, and names nextly upgrade.

Run nextly upgrade once the new release serves every instance. An instance still running the earlier release can store a password as it was written after the step has passed its row, so if you ran it during a rollout, run it again after the last earlier instance has stopped. A run that finds nothing left says so.

Core tables missing after an upgrade

A release can add tables to Nextly's own core schema. An existing database gets them only through nextly migrate (or a boot run with db.runMigrationsOnBoot); a production boot never creates tables. Until you run it, every boot logs one warning naming each missing core table, and whatever reads or writes those tables fails: deleting a document, for one, rolls back. Run nextly migrate after every upgrade, and the warning goes away.

Core schema drift after nextly upgrade

User migration files contain user-schema only — core system tables are owned by the Nextly package version and reconciled by nextly migrate Phase 1. If nextly migrate reports core schema drift after upgrading from a very early alpha (e.g. a hand-edited bundled file), run nextly upgrade --reconcile-core. It reconciles core in dev-loose mode and prompts for confirmation on each destructive operation it will make. It never drops a table or column of Nextly's own: such a drop is left in place and reported, not asked about, and with nothing else destructive to make it asks nothing. nextly upgrade --reconcile-core --dry-run names the statements it would run and the drops it would leave in place, changing nothing. Use it only when migrate reports core drift.

Rolling back a migration

nextly migrate:create writes a -- DOWN section into each generated migration (the inverse of its -- UP). nextly migrate:down reverts the most-recently applied migration using that section:

# Roll back the last migration
nextly migrate:down

# Roll back the last 3
nextly migrate:down --step 3

# Preview without executing
nextly migrate:down --dry-run

Rollback restores schema shape, not data. Reverting an added column drops it (and its data); reverting a dropped column re-adds an empty column — the old rows are gone. For this reason:

  • A migration whose DOWN drops a table or column requires --allow-data-loss.
  • In production (NODE_ENV=production), migrate:down requires --yes.
  • A migration with an empty -- DOWN (data-only or blank) is irreversible — migrate:down refuses it. Roll forward with a corrective migration instead.

After a successful rollback, the migration is recorded as rolled_back in nextly_schema_events and becomes pending again, so the next nextly migrate re-applies it.

A rollback whose DOWN fails is recorded as a file_rollback event, and the migration stays applied: on PostgreSQL and SQLite the DOWN ran in one transaction and was undone, so a later migrate:down or plugins uninstall starts from that same migration again. On MySQL each DDL statement commits as it runs, so part of the DOWN may have taken effect; nextly migrate:status lists every applied migration whose latest rollback failed, and flags the MySQL ones, so the schema can be checked before anything is run again.

In production, prefer rolling forward (a new corrective migration) or restoring from a backup. migrate:down is a manual, CLI-only break-glass tool; it never runs on boot.

Recovery via corrective migrations

migrate:down handles single-step rollback, but for production incidents the safer path is usually to roll forward -- write a new migration that fixes the previous one. Examples:

  • Accidentally added a NOT NULL column without a default and the deploy failed -> write a new migration that backfills the column then re-applies the constraint.
  • Renamed a column too aggressively and broke a downstream service -> write a new migration that adds the old column name back as a copy until consumers are updated.
  • Need to drop a table you added in a recent migration -> write a new migration with DROP TABLE.

The audit trail in nextly_schema_events keeps both rows, so post-incident review can see exactly what was applied when, and by which CI job.

Plugins with tables of their own

The phase order

1. Core reconcile        — Nextly's own tables
2. Plugin migrations     — each plugin's, in dependency order
3. App migrations        — your own files

All three run under one lock, and all three run before any plugin initialises. That last point is load-bearing: a plugin's init() hook queries its tables, and it used to run first. On an upgraded database the tables were still on their old shape, and the plugin failed on a column that did not exist yet.

Plugins go before the app because app migrations may index entity tables that plugins contribute, and an index on a table that does not exist is not a recoverable error.

Adoption: when the tables are already there

A plugin you installed in development has its tables already — dev push created them. The first nextly migrate on a deployment finds them present, and that is the ordinary case rather than a failure.

Each module is decided by comparing the live tables against its own two endpoints:

The database matchesWhat happens
the module's beforethe UP runs
the module's snapshotrecorded as applied; nothing runs
neitherrefused, with the difference named

The third row is why this is a comparison and not an existence check. A table created by push and then altered by hand matches neither, and running the UP against it would fail halfway — or succeed, against a shape nobody intended.

When something fails

The first failure stops the whole run. Later plugins and the app phase do not execute, because migrations after a failed one assume a database state that was never reached.

Two checksums

A plugin migration carries a checksum over its whole content — its name, schema version, SQL and table snapshots — and the ledger separately stores the sha256 of what actually ran.

Neither covers the other. The first catches a module edited after generation — the SQL that will run is not the SQL that was reviewed. It covers more than the SQL because the runner acts on the rest too: the name is the module's ledger key and decides its order, the schema version is recorded against the plugin's tables, and the snapshots decide whether a module is already applied — a module whose target matches the live schema is recorded as adopted without its SQL running. Editing any of them is refused exactly like editing the SQL. A hand-written module computes its checksum with migrationChecksum from nextly/schema-extension, passing the module itself without its checksum.

The second catches a module changed after it was applied, where the database no longer matches the file claiming to describe it. A regenerated module with a rewritten checksum passes the first and fails the second, which is exactly right.

Nothing drops a table it does not own

A migration is scanned before its first statement runs and refused whole if it drops or renames a table or a column belonging to another owner. An app migration dropping auth__identities is refused; plugin-auth's own down migration dropping it is not.

Who owns what comes from the owner registry (nextly_schema_owners):

  • Tables. A table belongs to the stream its owner row names, and a core table (users, media, …) to core. A table with no owner row — every collection, Single and component table, and any table your own migrations created — is your app's to drop, and never a plugin's: a plugin migration may drop only tables a row records as the plugin's, or a table the same module creates. A table the module creates counts only when no table of that name existed before the module ran (read from the database before the module is judged), and only when the module creates and drops it under the same unqualified, lower-case name (CREATE TABLE t, not CREATE TABLE scratch.t or CREATE TABLE "T"; SQLite's temp.t also counts). A CREATE naming a table that already exists cannot have made it, so a drop of that name after it is judged as a drop of the existing table. MariaDB's CREATE OR REPLACE TABLE t is read as a drop of t, unless no table t existed before the module ran, and then a creation of it. Nor does any table count once the module may change which table an unqualified name reaches: a PostgreSQL SET, RESET, DISCARD, set_config(), CREATE SCHEMA or ALTER SCHEMA, or a MySQL USE, anywhere in it — including inside a DO block or function body — makes every table it creates count as the table of that name it may reach instead.
  • Columns. A column added to another owner's table belongs to whoever added it, as its element row records. Any other column belongs to its table, except that your app may drop a column on a core table, since what is added to a core table rides your app's migrations.

The scan happens before execution rather than filtering statements during it, because a file with some statements removed would still be recorded as applied — the ledger would claim a migration ran that partly did not.

A complete SQLite table rebuild is not a drop: four adjacent statements — CREATE TABLE __new_t (…), INSERT INTO __new_t (columns) SELECT columns FROM t copying every column the new table declares, DROP TABLE t, ALTER TABLE __new_t RENAME TO t — keep the table and its rows under the same name. This is how SQLite adds a check or a foreign key, including one that an app or plugin contributes to a table another owner holds. The runner compares the new table with the columns the live table has when the migration runs — read from the database first, following any ADD/DROP/RENAME COLUMN earlier in the same file. A live column the new table leaves out is dropped by the rebuild, and judged as a column drop: this is how SQLite removes a column a check names, such as an enum you added to users. A new table declaring a column the live table lacks, or one whose live columns could not be read, is read as the drop of the table it may be. A lone DROP, a rename of the table, or a rebuild that filters, reorders or renames elsewhere is still refused. A migration that renames another owner's table (or moves it with PostgreSQL's SET SCHEMA) is refused like a drop.

On PostgreSQL, CASCADE on a DROP of anything but a table — a type, domain, extension, function, procedure, view, sequence or index, or an ALTER TYPE … DROP ATTRIBUTE — is refused. It also drops whatever depends on the object, such as every column of a dropped type or domain in whoever's table, and the text does not say which tables those are. Drop the columns or tables that use the object first, then the object without CASCADE: PostgreSQL refuses that drop while anything still depends on it. CASCADE on an ALTER TABLE's drop of a column or constraint is refused for the same reason: it also drops another table's foreign key on that column or key, or a view over it, which may be another owner's. A DROP SCHEMA is refused with or without CASCADE.

Development push never drops a plugin-migrated table at all, whatever your config says. A plugin removed from config is exactly when its data is most at risk, and that is a decision for nextly plugins uninstall rather than a side effect of a reload.

nextly migrate:fresh drops everything. The check above — that a migration dropping another owner's table is refused — applies to push, reconcile and migrate, within the limits below, and not to migrate:fresh.

Known limits

The drop check catches mistakes. It is not a security boundary: plugins are trusted code that already run in your process with database access, so nothing that reads their migration text can stop a plugin set on dropping a table. Two limits are accepted:

  • It reads SQL as text. Where it cannot read a statement with certainty it refuses it: an unterminated string or comment, a MySQL executable comment, and MySQL's backslash escape inside a string ('it\'s'), whose meaning depends on a server setting. Write the quote doubled ('it''s') instead. Code written as a string is refused too: EXECUTE and PREPARE, which run SQL assembled at run time, and on PostgreSQL a DO, CREATE FUNCTION or CREATE PROCEDURE whose body is a quoted string, such as CREATE FUNCTION f() RETURNS void AS 'DROP TABLE auth__identities' LANGUAGE sql. Write such bodies with $$ … $$, which is read as code. It does not read SQL passed as a string to a function that runs it: that is data to the check, so a drop inside it is not refused. Nor does it see what a PostgreSQL DROP TABLE … CASCADE, which generated migrations write, removes besides the table: the views and foreign keys that depend on it, and the tables that inherit from it (INHERITS). Only the named table is judged.
  • On MySQL, development push and an apply planned through drizzle-kit can commit a change before the check refuses. The checks that read drizzle-kit's plan run after the renames and drops that plan resolves first, and MySQL commits each schema statement as it runs. The next push plans again from the database as it now stands, and converges. nextly migrate is not affected: a migration's statements are fixed and checked before any of them runs.

Boot refusals you may meet

CodeMeaning
PLUGIN_SCHEMA_BEHINDThe plugin expects a newer schema than the database has. Run nextly migrate.
PLUGIN_NOT_INSTALLEDAn enabled plugin in your config has not been installed on this database. Run nextly plugins install <name> for each one it names, or nextly plugins install --all. A disabled plugin is not required to be installed: its tables exist, but its onInstall runs only when you enable and install it.
PLUGIN_SCHEMA_UNINSTALLEDThe plugin was uninstalled, with or without --keep-data, but is still in your config. Reinstall it or remove the line.
PLUGIN_UNINSTALL_UNFINISHEDAn uninstall of the plugin began and did not finish. Run it again, the way it began, to finish it, or reinstall the plugin.
PLUGIN_MIGRATIONS_UNAVAILABLEA plugin declares tables and ships no migrations to create them.
MIGRATION_CHECKSUM_MISMATCHA migration changed after it was generated or applied.
DROP_OF_FOREIGN_TABLEA migration would drop or rename another owner's table, column, index, foreign key or check, or a plugin migration a table no owner row claims. Nothing was applied.

In development, PLUGIN_SCHEMA_BEHIND and PLUGIN_NOT_INSTALLED only log: push reconciles from config on every reload, so a schema behind resolves itself moments later, and a plugin is added to the config and tried before anyone installs it. The other refusals hold in every environment. The install-state refusals come before boot migrations run, so a refused plugin's modules are not applied first.

Ledger commands and plugin rows

migrate:down and migrate:status ignore plugin rows by default, and take --plugin <name> to select one plugin's. migrate:resolve takes no such flag: it acts on the one migration it is given, and a plugin module is named by its ledger key, plugin:<name>/<module> (for example nextly migrate:resolve --failed-cleanup plugin:@acme/auth/20260101_000000_init). --applied refuses a plugin module, because nextly migrate records a module together with the tables it owns: clear its failed attempt with --failed-cleanup and run nextly migrate. migrate:check does not read the ledger at all; it checks the app's migration files and snapshots.

migrate:status --plugin <name> lists the modules the configured plugin ships beside its ledger rows, as the app's listing does with its files: a module no run has applied yet shows as pending, and a recorded module the plugin no longer ships shows as applied with its file missing.

The default matters: migrate:down picks the newest applied migration of any kind, so without the exclusion it would revert a plugin's migration while reporting an app rollback.

Installing

A plugin is installed on a database once nextly plugins install <name> has run there and finished: it applies the plugin's pending modules, runs its onInstall, and records the plugin installed. nextly migrate applies a plugin's modules too, but never runs onInstall, so it does not install the plugin. A production boot refuses an enabled plugin that has not been installed (PLUGIN_NOT_INSTALLED), whether or not migrations run at boot. A disabled plugin (enabled: false) boots without an install; once you enable it, the boot requires one.

So, for every enabled plugin in your config, run the install command once on each database, after nextly migrate, before the first production boot that includes the plugin. Running it again is safe: it applies what is pending and calls onInstall again, which is why onInstall has to be idempotent. Each run also records which tables the plugin owns and which columns, indexes, keys and checks its modules added to other owners' tables, so an install run again after one that stopped part way records whatever that run did not. nextly plugins install --all runs it for every enabled plugin in your config, in dependency order, and stops at the first that fails; a disabled plugin is skipped and named.

That makes the build the place to run it, against the database the build targets. A project from create-nextly-app does so already: its build script installs each plugin its config registers. Adding a plugin to an existing app? Add its install to your build, after nextly migrate:

nextly migrate && nextly plugins install <name> && next build

Each run of an install records one row in nextly_schema_events and changes nothing else that is already in place. When you remove a plugin from nextly.config.ts, remove its nextly plugins install from your build script, since installing a plugin that is not configured fails the build. Install plugins that depend on others after them, as dependsOn lists them.

A plugin's install also refuses while a plugin it depends on is not installed (PLUGIN_DEPENDENCY_NOT_INSTALLED): one never installed, uninstalled, or whose uninstall has not finished. That holds for a dependency that owns no tables too, whose install record is the only trace it leaves.

Uninstalling

nextly plugins uninstall <name> needs the plugin still in your config — its DOWN sections are its own code, so a plugin removed from config first cannot be uninstalled at all.

It refuses while another enabled plugin depends on it, or a disabled one requires it, and refuses a full uninstall when any module has no DOWN: running the reversible ones and stopping would leave the tables partly existing with no module describing what is there. It refuses the same way while the ledger records a module applied that the configured version of the plugin no longer ships (logContext.reason is module-not-shipped): configure the version that shipped it first. --keep-data leaves everything in place and marks the owner orphaned. A plugin whose modules migrate:down --plugin already rolled back can still be uninstalled: only the tables that exist are dropped.

The DOWN statements are read before any runs, in the order they will run, following each table through renames. DOWNs that leave one of the plugin's tables in place are refused (logContext.reason is down-leaves-tables): a table no statement drops, one only rebuilt, one renamed away and kept, or one whose name another table takes after its drop. Fix the plugin's DOWN, or use --keep-data.

Only the statements a generated DOWN is made of are read this way: dropping, altering and creating tables and indexes, type and sequence statements, data statements, and a SQLite rebuild. A DOWN holding anything else (a savepoint, a procedural block, a view, a temporary table) or a schema-qualified name such as temp.notes is refused the same way, since what it drops cannot be read from its text. So are a plugin's tables whose stored names keep upper case, on PostgreSQL and MySQL. If onUninstall drops or renames one of the tables the DOWNs are to drop, the uninstall stops before the first DOWN (tables-changed-by-hook). If a table is still there after the DOWNs ran, the plugin is not recorded as uninstalled (tables-left-by-down); drop the table and run the uninstall again.

plugins install holds the migrate lock from its first migration until onInstall returns, and plugins uninstall from its final decision until the owner rows are marked, so neither can interleave with the other or with nextly migrate. The boot each command makes to run the hook never runs boot migrations.

Each command records the plugin's state as an event in the migration ledger, so a plugin that owns no tables has one too. An uninstall records that it has begun before its first change, and that it has finished, uninstalled or, with --keep-data, orphaned, at its end. Until the plugin leaves your config, the boot refuses it in every environment: PLUGIN_SCHEMA_UNINSTALLED once the uninstall finished, PLUGIN_UNINSTALL_UNFINISHED while it has not.

An uninstall that stops part way, after some of its DOWNs have committed, is finished by running it again the same way, with or without --keep-data as before: it plans over the modules still applied and the tables still there, calls onUninstall again, and carries on. Run the other way, it is refused (PLUGIN_UNINSTALL_UNFINISHED). onUninstall has to be idempotent for this reason. nextly plugins install reinstates the plugin instead.

A full uninstall that would drop tables, or run a DOWN that drops a column, lists what it would drop and stops with PLUGIN_UNINSTALL_UNCONFIRMED until you re-run it with --yes. Each module's DOWN is read, judged and run exactly as migrate:down --plugin runs it, newest first. Tables that a development push created, with no applied migration module to undo them, are refused with PLUGIN_UNINSTALL_IRREVERSIBLE (logContext.reason is no-applied-module): drop them with a migration, or reset the development database. Every refusal — these, a dependent plugin, a module that fails its checksum, a DOWN that would drop another owner's table — is decided before the migrate lock is taken and before onUninstall or any DOWN runs, so a refused uninstall changes nothing.