Run D1 migrations
import { Steps, Aside } from ‘@astrojs/starlight/components’;
For each D1 binding in a Worker’s wrangler.jsonc, the plugin infers a d1 target with create, apply, and list configurations that wrap wrangler d1 migrations. Use them to evolve your D1 schema from local development through to production.
Before you start
Section titled “Before you start”- A Worker with a D1 binding in
wrangler.jsonc. Add one with the binding generator:bunx nx g @naxodev/nx-cloudflare:binding --project=my-worker --type=d1 --binding=DB --databaseName=app-db --id=<database-id>. - D1 targets are inferred from
wrangler.jsonc/wrangler.jsononly — notwrangler.toml.
-
Create a migration
bunx nx run my-worker:d1:create --message=create_usersThis writes a timestamped
.sqlfile in the database’s migrations directory (migrations/by default). -
Write the SQL
Edit the generated file under
migrations/:CREATE TABLE users ( id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE ); -
Apply locally
bunx nx run my-worker:d1:applyd1:applydefaults to--local, so this runs against the local database used bynx run my-worker:serve(wrangler dev). -
Apply to production
bunx nx run my-worker:d1:apply --remoteThe
--remoteflag runs the pending migrations against the live D1 database.
Variations
Section titled “Variations”List pending migrations
Section titled “List pending migrations”bunx nx run my-worker:d1:list # local
bunx nx run my-worker:d1:list --remote # remote
Multiple D1 databases
Section titled “Multiple D1 databases”When a Worker declares more than one d1_databases binding, select which one a command targets with --db=<binding>:
bunx nx run my-worker:d1:apply --db=ANALYTICS --remote
With a single D1 database, --db is optional. With multiple, omitting it errors and lists the valid bindings.
Target an environment
Section titled “Target an environment”Any d1:apply/d1:list invocation accepts --env for a Wrangler environment:
bunx nx run my-worker:d1:apply --remote --env=production
Apply migrations during deploy
Section titled “Apply migrations during deploy”The plugin does not chain migrations into deploy automatically. To apply before deploying in CI, run them in sequence:
bunx nx run my-worker:d1:apply --remote && bunx nx run my-worker:deploy
Verify
Section titled “Verify”After applying, d1:list reports no pending migrations:
bunx nx run my-worker:d1:list --remote
Next steps
Section titled “Next steps”- Manage Worker secrets — the other Day-2 workflow
- binding generator — add the D1 binding these targets operate on
- Inferred targets — the full
d1target and option reference