DEV Community

Cover image for Drizzle D1 Workflow: Local Migrations That Match Prod
Saiful Islam
Saiful Islam

Posted on

Drizzle D1 Workflow: Local Migrations That Match Prod

The same SQLite schema, three apply paths, and a seed command that silently picks production when you forget one variable.

The Problem

You want to reset staging with fresh roles. You copy a seed command, omit one variable, and run it:

SEED_REMOTE=true WRANGLER_CONFIG_PATH="wrangler.seed.jsonc" \
  tsx ./src/db/seed/dev-seed/index.ts
Enter fullscreen mode Exit fullscreen mode
๐ŸŒฑ Starting database seed...
๐Ÿ”Œ Connecting to the REMOTE (production) D1 database ...
๐Ÿงน Clearing existing data...
๐Ÿ—‘๏ธ  Cleared existing data
Enter fullscreen mode Exit fullscreen mode

The cause is one line in the seed client:

const isRemote = process.env.SEED_REMOTE === "true";
const seedEnvironment = process.env.SEED_ENV || "production";
const { env, dispose } = await getPlatformProxy({
  configPath: process.env.WRANGLER_CONFIG_PATH,
  environment: isRemote ? seedEnvironment : undefined,
  remoteBindings: isRemote,
});
await clearAll(createDrizzleClient(env.DB));
Enter fullscreen mode Exit fullscreen mode

Three fixes you try first:

  1. Flip remote to false in the production binding. Now local development writes through a flag meant for production; the flag configures the binding, not your intent.
  2. Run drizzle-kit migrate with the HTTP config for every target. It applies SQL but bypasses D1's own migration ledger, so two tools claim to own the applied-version list.
  3. Check the ENVIRONMENT variable inside the seed. That value lives on the Worker binding, not in the Node process launching the seed, so the guard never fires.

You need one schema definition to drive three databases, but each target is reached through a different door, and the door decides which rows get deleted.

The shape of the fix is to make the target explicit and fail closed:

const isRemote = process.env.SEED_REMOTE === "true";
const target = isRemote ? process.env.SEED_ENV : "local";
if (isRemote && !target) {
  throw new Error("SEED_ENV is required for remote seeds");
}
Enter fullscreen mode Exit fullscreen mode

The Mental Model

Think air traffic control.

  • Identity: migration files are numbered flight plans; migrations_dir is the plan number on file.
  • Update timing: wrangler d1 migrations apply is the tower granting clearance. drizzle-kit generate only writes plans.
  • Read timing: the DB binding is the runway a request lands on. Code sees the same name at every airport.

Two consequences: a plan filed for the wrong runway lands at the wrong airport, and a binding called DB tells you nothing about which database sits behind it. The ledger table is the tower's log, so an already-cleared plan is not flown twice.

Runway number is not a destination; binding name is not a database.

How to Use It

The schema folder, generators, column helpers, and seed split are exactly the plain SQLite setup described in Drizzle SQLite Setup: One Schema, No Drift. D1 changes the client, one config file, and the apply path. Nothing in src/db/schemas/** changes.

Install:

pnpm add drizzle-orm
pnpm add -D drizzle-kit wrangler @libsql/client dotenv tsx
Enter fullscreen mode Exit fullscreen mode

File tree:

src/
โ””โ”€โ”€ db/
    โ”œโ”€โ”€ clients/
    โ”‚   โ”œโ”€โ”€ drizzle-client.ts
    โ”‚   โ””โ”€โ”€ drizzle-client.mock.ts
    โ”œโ”€โ”€ schemas/
    โ”‚   โ””โ”€โ”€ index.ts
    โ”œโ”€โ”€ seed/
    โ”‚   โ””โ”€โ”€ seed-db.client.ts
    โ””โ”€โ”€ utils/
        โ””โ”€โ”€ chunk-by-params.ts
drizzle.config.ts
drizzle.local.config.ts
wrangler.jsonc
Enter fullscreen mode Exit fullscreen mode

Imports below use @/. Swap in whatever alias your project uses.

wrangler.jsonc โ€” the same binding name at three airports, with one ledger table:

{
  "compatibility_date": "2026-11-17",
  "compatibility_flags": ["nodejs_compat"],
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "db-local",
      "database_id": "00000000-0000-0000-0000-000000000000",
      "migrations_dir": "migrations",
      "migrations_table": "d1_migrations",
      "remote": false,
    },
  ],
  "env": {
    "staging": {
      "d1_databases": [
        {
          "binding": "DB",
          "database_name": "db-stage",
          "database_id": "00000000-0000-0000-0000-000000000000",
          "migrations_dir": "migrations",
          "migrations_table": "d1_migrations",
          "remote": true,
        },
      ],
    },
    "production": {
      "d1_databases": [
        {
          "binding": "DB",
          "database_name": "db",
          "database_id": "00000000-0000-0000-0000-000000000000",
          "migrations_dir": "migrations",
          "migrations_table": "d1_migrations",
          "remote": true,
        },
      ],
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

drizzle.config.ts โ€” for remote introspection and Studio, not for applying migrations:

import { config } from "dotenv";
import { defineConfig } from "drizzle-kit";

config();

export default defineConfig({
  schema: "./src/db/schemas/**",
  out: "migrations",
  dialect: "sqlite",
  driver: "d1-http",
  dbCredentials: {
    accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
    databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
    token: process.env.CLOUDFLARE_D1_TOKEN!,
  },
});
Enter fullscreen mode Exit fullscreen mode

drizzle.local.config.ts โ€” finds the database file the local platform created:

import { existsSync, readdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { defineConfig } from "drizzle-kit";

function findLocalDbFile() {
  const dir = resolve(
    process.cwd(),
    ".wrangler/v3/d1/miniflare-D1DatabaseObject",
  );
  if (!existsSync(dir)) throw new Error("Run the local migration first");
  const file = readdirSync(dir).find(
    (name) => name.endsWith(".sqlite") && name !== "metadata.sqlite",
  );
  if (!file) throw new Error("No local database file found");
  return join(dir, file);
}

export default defineConfig({
  schema: "./src/db/schemas/**",
  out: "migrations",
  dialect: "sqlite",
  dbCredentials: { url: findLocalDbFile() },
});
Enter fullscreen mode Exit fullscreen mode

src/db/clients/drizzle-client.ts โ€” the binding, never a URL:

import {
  type AnyD1Database,
  drizzle,
  type DrizzleD1Database,
} from "drizzle-orm/d1";

import * as schema from "@/db/schemas";

export type DatabaseType = DrizzleD1Database<typeof schema>;

export function createDrizzleClient(db: AnyD1Database): DatabaseType {
  return drizzle(db, { schema });
}
Enter fullscreen mode Exit fullscreen mode

src/db/seed/seed-db.client.ts with the fail-closed guard:

import { getPlatformProxy } from "wrangler";
import { createDrizzleClient } from "../clients/drizzle-client";

type SeedEnv = { DB: Parameters<typeof createDrizzleClient>[0] };

export async function seedDbClient() {
  const configPath = process.env.WRANGLER_CONFIG_PATH;
  const isRemote = process.env.SEED_REMOTE === "true";
  const target = isRemote ? process.env.SEED_ENV : "local";
  if (isRemote && !target)
    throw new Error("SEED_ENV is required for remote seeds");

  const { env, dispose } = await getPlatformProxy<SeedEnv>({
    configPath,
    environment: target === "local" ? undefined : target,
    remoteBindings: isRemote,
    persist: isRemote
      ? false
      : process.env.WRANGLER_PERSIST_PATH
        ? { path: process.env.WRANGLER_PERSIST_PATH }
        : false,
  });

  return { db: createDrizzleClient(env.DB), dispose, target };
}
Enter fullscreen mode Exit fullscreen mode

src/db/clients/drizzle-client.mock.ts โ€” the local test double speaks the same D1 subset:

import { createClient } from "@libsql/client";
import { drizzle, type AnyD1Database } from "drizzle-orm/d1";

import * as schema from "@/db/schemas";
import type { DatabaseType } from "./drizzle-client";

function createStatement(client: ReturnType<typeof createClient>, sql: string) {
  let args: unknown[] = [];
  const statement = {
    sql,
    get args() {
      return args;
    },
    bind(...values: unknown[]) {
      args = values;
      return statement;
    },
    async all() {
      return client.execute({ sql, args: args as never[] });
    },
    async run() {
      return client.execute({ sql, args: args as never[] });
    },
    async first() {
      const result = await client.execute({ sql, args: args as never[] });
      return result.rows[0] ?? null;
    },
    async raw() {
      return (await client.execute({ sql, args: args as never[] })).rows;
    },
  };
  return statement;
}

export function createMockDrizzleClient(): DatabaseType {
  const client = createClient({ url: ":memory:" });
  const database = {
    prepare: (sql: string) => createStatement(client, sql),
    async batch(statements: Array<ReturnType<typeof createStatement>>) {
      return client.batch(
        statements.map(({ sql, args }) => ({ sql, args: args as never[] })),
        "write",
      );
    },
    async exec(query: string) {
      await client.executeMultiple(query);
      return { count: 0, duration: 0 };
    },
  } as unknown as AnyD1Database;

  return drizzle(database, { schema });
}
Enter fullscreen mode Exit fullscreen mode

src/db/utils/chunk-by-params.ts โ€” the budget is 100, not 999:

const MAX_BOUND_PARAMS = 100;

type PendingQuery<T> = PromiseLike<T> & { toSQL(): { params: unknown[] } };

export async function insertChunked<T, R>(
  rows: T[],
  build: (chunk: T[]) => PendingQuery<R>,
): Promise<R[]> {
  if (!rows.length) return [];
  const query = build(rows);
  if (rows.length === 1 || query.toSQL().params.length <= MAX_BOUND_PARAMS) {
    return [await query];
  }
  const mid = Math.ceil(rows.length / 2);
  return [
    ...(await insertChunked(rows.slice(0, mid), build)),
    ...(await insertChunked(rows.slice(mid), build)),
  ];
}
Enter fullscreen mode Exit fullscreen mode

package.json scripts โ€” one generator, three apply paths, three seed targets:

{
  "scripts": {
    "db:generate": "drizzle-kit generate",
    "db:studio:local": "drizzle-kit studio --config=\"drizzle.local.config.ts\"",
    "db:studio:prod": "drizzle-kit studio --config=\"drizzle.config.ts\"",
    "db:migrate:local": "wrangler d1 migrations apply db-local --local --persist-to=\".wrangler\" --config=\"wrangler.jsonc\"",
    "db:migrate:stage": "wrangler d1 migrations apply db-stage --remote --env staging --config=\"wrangler.jsonc\"",
    "db:migrate:prod": "wrangler d1 migrations apply db --remote --env production --config=\"wrangler.jsonc\"",
    "db:seed:local": "WRANGLER_CONFIG_PATH=\"wrangler.seed.jsonc\" WRANGLER_PERSIST_PATH=\".wrangler/v3\" tsx ./src/db/seed/dev-seed/index.ts",
    "db:seed:stage": "SEED_REMOTE=true SEED_ENV=staging WRANGLER_CONFIG_PATH=\"wrangler.seed.jsonc\" tsx ./src/db/seed/stage-seed/index.ts",
    "db:seed:prod": "SEED_REMOTE=true SEED_ENV=production WRANGLER_CONFIG_PATH=\"wrangler.seed.jsonc\" tsx ./src/db/seed/prod-seed/index.ts"
  }
}
Enter fullscreen mode Exit fullscreen mode

Pattern 1: Generate once, fly the plan three times

pnpm db:generate        # writes migrations/0001_*.sql from schemas/**
pnpm db:migrate:local   # local file, --local --persist-to
pnpm db:migrate:stage   # remote, --env staging
pnpm db:migrate:prod    # remote, --env production
Enter fullscreen mode Exit fullscreen mode

The same SQL files are applied in order; the d1_migrations ledger in each database decides which ones still need flying.

Pattern 2: Seed a target you named yourself

import { seedDbClient } from "../seed-db.client";

async function main() {
  const { db, dispose, target } = await seedDbClient();
  try {
    console.log(`Seeding ${target}`);
    // seedRoles(db); seedPermission(db); seedRolePermission(db, roles, permissions);
  } finally {
    await dispose();
  }
}

main();
Enter fullscreen mode Exit fullscreen mode

Printing the resolved target before the first delete makes a wrong airport visible in the log.

Pattern 3: Query through the injected binding

import { eq } from "drizzle-orm";
import { createDrizzleClient } from "@/db/clients/drizzle-client";
import { UserTable } from "@/db/schemas";

export async function handleRequest(env: {
  DB: Parameters<typeof createDrizzleClient>[0];
}) {
  const db = createDrizzleClient(env.DB);
  return db.query.UserTable.findMany({
    where: eq(UserTable.email, "ada@example.com"),
    with: { sessions: true },
  });
}
Enter fullscreen mode Exit fullscreen mode

No URL, token, or environment switch appears in application code; the platform supplies the runway.

Pattern 4: Test the same queries on a local file

import { expect, test } from "vitest";
import { createMockDrizzleClient } from "@/db/clients/drizzle-client.mock";
import { UserTable } from "@/db/schemas";

test("queries run against the D1-shaped mock", async () => {
  const db = createMockDrizzleClient();
  const rows = await db.select().from(UserTable);
  expect(rows).toEqual([]);
});
Enter fullscreen mode Exit fullscreen mode

The mock implements only prepare, batch, and exec, which is all the Drizzle D1 driver touches.

โŒ Do not apply migrations with drizzle-kit migrate against drizzle.config.ts in production: it writes SQL without recording it in D1's own ledger, so a later Wrangler apply replays work.

When to Use It

Reach for this setup only when all three are true:

  • Your app runs where a DB binding is injected, and you accept that shape in application code.
  • Local, staging, and production must share one schema but cannot share one database file.
  • You can keep every multi-row write under 100 bound parameters.
Situation Better tool
Plain Node server with a file The SQLite config setup linked above
Browser-only storage IndexedDB
Need ILIKE or full-text ranking Postgres, or SQLite FTS on a plain file
More than 100 bound parameters per write Batched statements or a different driver
Need Studio against one remote database The d1-http config shown above
Migrations must stay in a platform ledger wrangler d1 migrations apply

Smell test: if two tools can mark a migration as applied, you do not have a ledger, you have a rumour.

How It Works Under the Hood

  1. One glob feeds both sides. schema: "./src/db/schemas/**" drives Kit's generated SQL, and drizzle(db, { schema }) drives the runtime client. Generate from the same files you import at request time.
  2. Two configs, one dialect. Both configs set dialect: "sqlite". The local one passes a file url; the remote one passes accountId, databaseId, and token with driver: "d1-http". SQL is generated once; the configs choose where you inspect it.
  3. Wrangler owns the ledger. migrations_dir: "migrations" appears in all three env blocks and migrations_table: "d1_migrations" records applied versions per database. That is why apply is idempotent and why a second applier creates drift.
  4. The binding hides credentials. createDrizzleClient(env.DB) accepts AnyD1Database. Application code cannot accidentally point at a different database, which is also why the seed process is the dangerous one: it resolves the binding outside the app.
  5. getPlatformProxy decides the target. remoteBindings chooses remote data, environment chooses the env block, and persist points local writes at a directory. With SEED_ENV defaulting to production, an unset variable is a destructive choice, so fail closed.
  6. The mock is an adapter, not a fork. libSQL's :memory: database is wrapped in prepare, batch, and exec with a D1Database shape, then handed to drizzle-orm/d1. Tests use the same schema and query code as production.
  7. Search stays SQLite-compatible. buildSearchWhere uses LIKE with an escaped % and _, not ILIKE, because D1 does not implement ILIKE. Chunking measures toSQL().params and halves recursively at 100.
Phase Local Staging Production Failure if wrong
Generate same migrations/*.sql same files same files stale schema
Apply --local --persist-to --remote --env staging --remote --env production wrong database
Ledger d1_migrations d1_migrations d1_migrations replayed migration
Seed WRANGLER_PERSIST_PATH SEED_ENV=staging SEED_ENV=production deleted rows
Read injected DB injected DB injected DB no URL to blame
Test mock :memory: mock :memory: mock :memory: different query code

In a server-rendered React app, build the client from the binding on the request's server side. getPlatformProxy is a CLI helper for seeds; importing it into application code would give the app a second, untracked path to the database.

Drizzle Kit's built-in migrate can talk to D1 over HTTP, but it cannot see D1's d1_migrations ledger. Treat that as a limitation: use Kit to generate and inspect, and Wrangler to apply.

Conclusion

The win is a single schema definition with three explicit apply paths. The cost is that every path must name its target out loud: migration commands carry --env, seeds carry SEED_ENV, and the ledger lives inside each database rather than in your repository.

  • Generate from schemas/** and apply the same ordered files everywhere.
  • Let Wrangler own the migration ledger; use Studio only to inspect.
  • Fail closed when a remote seed has no named environment.

Use this when the platform owns apply and your code sees only a binding. When you own the whole database yourself, the plain SQLite setup is the boring, better answer.

Top comments (0)