Drizzle D1 Workflow: Local Migrations That Match Prod
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
๐ฑ Starting database seed...
๐ Connecting to the REMOTE (production) D1 database ...
๐งน Clearing existing data...
๐๏ธ Cleared existing data
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));
Three fixes you try first:
- 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.
- 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.
- 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");
}
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
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
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
}
]
}
}
}
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!,
},
});
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() },
});
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 });
}
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 };
}
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 });
}
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)),
];
}
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"
}
}
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
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();
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, "a**@example.com"),
with: { sessions: true },
});
}
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([]);
});
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
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.
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.
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.
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.
getPlatformProxy decides the target. remoteBindings chooses remote data, envir
Comments
No comments yet. Start the discussion.