Cloudflare D1
Cloudflare D1 is a managed SQLite database running at the edge, accessed through the Workers binding API.
What create-faster adds
D1 requires --deployment cloudflare — the DB binding is injected by the Workers runtime, so there is no connection string. create-faster wires this binding end-to-end across every generated file.
D1 works with or without an ORM. Without one, create-faster declares the DB binding, the provisioning steps and (on Next.js) the getEnv seam, and generates no migration script and no database client: bring your own client, or a framework that owns the schema and its migrations. With Drizzle (--orm drizzle) it also generates everything below that names a schema, a db factory, drizzle.config.ts, the .env.d1.example credentials or a db:* script.
wrangler.jsonc — D1 binding declaration:
"d1_databases": [
{
"binding": "DB",
"database_name": "{projectName}-db",
"database_id": "REPLACE_WITH_D1_DATABASE_ID",
"migrations_dir": "drizzle"
}
]migrations_dir is written with Drizzle only.
Replace REPLACE_WITH_D1_DATABASE_ID with the id returned by wrangler d1 create. In a Turborepo every app binds the same database ({projectName}-db) so the apps see the same data and migrations target one database: paste the same id into each app's wrangler.jsonc.
Provisioning the production database
The generated README and AGENTS.md list these steps with the exact commands of the package manager you picked (bunx, npx or pnpm exec run the project's own Wrangler). Steps 3 and 4 print migration scripts, which come with Drizzle: without an ORM they are left out and the deploy is step 3.
- Create the database:
npx wrangler d1 create {projectName}-db --no-update-config. In a Turborepo run it from an app directory,(cd apps/<app> && npx wrangler d1 create ...): the root links no Wrangler.--no-update-configstops Wrangler from offering to add the binding towrangler.jsoncitself; accepting would add a second binding named after the database next toDB, which the code never reads. - Paste the printed
database_id(keep the bindingDB) intowrangler.jsonc, in every app of a Turborepo. - With Drizzle, run
db:generate(the template ships no migration; it changes nothing when they exist) anddb:migrateagain (anddb:seedif you had seeded). Miniflare keys the local D1 file bydatabase_id, so the real id switches local development to a new, empty database until it is migrated. - With Drizzle, run
db:migrate:remoteto create the tables in the production database (the Turborepo root script runs it insidepackages/db). Without it the deployed app fails withno such table. - Set what
wrangler.jsoncrequires, then deploy: a deploy fails until every name undersecrets.requiredis set (Better Auth addsBETTER_AUTH_SECRETandBETTER_AUTH_URL, the production URL of the Worker, which Cloudflare shows how to learn before the first deploy) and every other bound resource, such as an R2 bucket, exists. Then run the build and deploy commands of the generated README.
src/lib/db/index.ts — factory, not singleton:
D1 is injected per request, not available at module load time. The generated client is a createDb factory that accepts the binding:
import { drizzle } from 'drizzle-orm/d1';
import * as schema from './schema';
export function createDb(d1: D1Database) {
return drizzle(d1, { schema });
}
export type Database = ReturnType<typeof createDb>;- Single repo:
src/lib/db/index.ts - Turborepo:
packages/db/src/index.ts
src/lib/env.ts (Next.js only) — getEnv seam:
For Next.js apps, a getEnv helper retrieves the binding from the OpenNext Cloudflare context:
import 'server-only';
import { getCloudflareContext } from '@opennextjs/cloudflare';
import { connection } from 'next/server';
export type Env = { DB: D1Database };
export async function getEnv(): Promise<Env> {
await connection();
const { env } = await getCloudflareContext({ async: true });
return { DB: env.DB };
}connection() makes next build skip prerendering a page that reads the binding. Without it, every build worker that renders such a page starts a local workerd on the local D1 state, and several of them opening it at once can fail with SQLITE_BUSY.
Call getEnv() in Server Components or Route Handlers, then pass env.DB to createDb:
const env = await getEnv();
const db = createDb(env.DB);src/lib/server.ts — the app's db and auth:
When the app also selects an ORM (and optionally Better Auth), create-faster generates an app-side module that composes the binding into ready-to-use instances. Next.js builds them per request:
import 'server-only';
import { nextCookies } from 'better-auth/next-js';
import { createDb } from '@/lib/db';
import { createAuth } from '@/lib/auth/create-auth';
import { getEnv } from '@/lib/env';
export async function getDb() {
return createDb((await getEnv()).DB);
}
export async function getAuth() {
return createAuth(await getDb(), nextCookies());
}TanStack Start reads the binding from cloudflare:workers and builds them once at module scope, which the D1 binding allows:
import { tanstackStartCookies } from 'better-auth/tanstack-start';
import { env } from 'cloudflare:workers';
import { createDb } from '@/lib/db';
import { createAuth } from '@/lib/auth/create-auth';
export const db = createDb(env.DB);
export const auth = createAuth(db, tanstackStartCookies());In a turborepo the factories come from @repo/db and @repo/auth/auth.
Better Auth & tRPC on D1
Because the db package exports a createDb(d1) factory instead of a module-level db, Better Auth and tRPC receive the database instead of importing a singleton:
- Better Auth exports a
createAuth(db: Database, cookiePlugin?: BetterAuthPlugin)factory (src/lib/auth/create-auth.ts, orpackages/auth/src/auth.tsin a turborepo) with the shared config. The app builds its instance insrc/lib/server.tswith its framework's cookie plugin: the Next.js auth route handler resolves it per request viaawait getAuth(), the TanStack Start route imports the module-levelauth. - tRPC (
init.ts/packages/api/src/trpc.ts) takes thedbin its context and buildsauth = createAuth(db)insidecreateTRPCContext, without a cookie plugin, so tRPC session reads never refresh the session. The Server Component caller and the route handler supply it withdb: await getDb().
This is fully supported in both single-repo and turborepo modes:
bunx create-faster myapp \
--app web:nextjs:trpc,better-auth \
--database d1 \
--orm drizzle \
--deployment cloudflaredrizzle.config.ts — sqlite dialect with d1-http prod branch:
The config uses the sqlite dialect locally (pointing at the miniflare D1 file) and switches to the d1-http driver in production:
const isProduction = process.env.NODE_ENV === 'production';
export default defineConfig({
dialect: 'sqlite',
...(isProduction
? {
driver: 'd1-http',
dbCredentials: {
accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
databaseId: process.env.CLOUDFLARE_D1_DATABASE_ID,
token: process.env.CLOUDFLARE_API_TOKEN,
},
}
: { dbCredentials: { url: getLocalD1DB() ?? '' } }),
});Schema uses sqliteTable from drizzle-orm/sqlite-core — identical to the SQLite option. Schemas carry over unchanged between local and D1.
Environment Variables
Generated in .env.d1.example (turborepo: packages/db/.env.d1.example; single repo: root .env.d1.example):
CLOUDFLARE_ACCOUNT_ID="" # Cloudflare account id (drizzle-kit d1-http)
CLOUDFLARE_D1_DATABASE_ID="" # D1 database id from `wrangler d1 create`
CLOUDFLARE_API_TOKEN="" # Cloudflare API token with D1 edit permissionThese are account credentials that only drizzle-kit needs, when it runs with NODE_ENV=production against the remote D1 database through d1-http. Copy the file to .env.d1, which drizzle.config.ts loads (variables already set in the shell win) and which is git-ignored. The file is deliberately not named .env: Wrangler and the frameworks load .env into the Worker environment (a Next.js build through OpenNext even bundles it into the Worker), so the token would be readable by Worker code and end up in build output such as dist/server/.dev.vars. Local development uses the miniflare SQLite file and needs none of this.
db:migrate:remote runs wrangler, which authenticates on its own: wrangler login, or CLOUDFLARE_API_TOKEN exported in the shell (CI).
Workflow Scripts
These scripts are generated with Drizzle. Without an ORM the project has none of them, and no local-setup.
| Script | Purpose |
|---|---|
db:generate | Generate migration SQL from schema changes (drizzle-kit generate) |
db:migrate / db:migrate:local | Apply migrations to the local D1 |
db:migrate:remote | Apply migrations to the production D1 database |
local-setup | First-time local setup: generate the migrations, apply them, seed |
Single repo — everything is co-located at the project root, so migrate runs against the root wrangler.jsonc and the local state at ./.wrangler.
Turborepo — the migration SQL lives in packages/db/drizzle, but the D1 binding lives in the consuming app's wrangler.jsonc. The migrate scripts (in packages/db) therefore point wrangler at that app's config and persist to a single shared state dir at the workspace root:
wrangler --config ../../apps/<app>/wrangler.jsonc d1 migrations apply DB --local --persist-to ../../.wranglerThe app's wrangler.jsonc sets migrations_dir to ../../packages/db/drizzle, and opennextjs-cloudflare preview runs with the same --persist-to ../../.wrangler — so migrate, preview, and drizzle.config.ts all read and write the one local database. Run turbo db:migrate (or bun run db:migrate at the root) to apply migrations across the workspace.
Local development
--persist-to <dir> stores the local miniflare D1 under <dir>/v3/d1/. The generated drizzle.config.ts auto-discovers the latest SQLite file in .wrangler/v3/d1/ (root .wrangler/v3/d1/ in turborepo), so db:push and db:studio work without any env var once migrations have been applied.
Manual smoke test after local-setup:
bun run db:migrate # apply migrations to the local D1
bun run preview # build + start the Worker with the local D1 bindingORM
D1 works without an ORM, with Drizzle, or with a framework that owns its schema. Prisma is not supported on D1: --database d1 --orm prisma is rejected at validation time, and the interactive ORM prompt only offers compatible options. Better Auth needs an ORM, so it requires --orm drizzle here.
bunx create-faster myapp \
--app myapp:nextjs \
--database d1 \
--orm drizzle \
--deployment cloudflareWithout an ORM, drop --orm drizzle:
bunx create-faster myapp \
--app myapp:nextjs \
--database d1 \
--deployment cloudflare
