Last active
October 8, 2025 05:33
-
-
Save ixahmedxi/9ad9f19c04c9ed85c7a5a29521099956 to your computer and use it in GitHub Desktop.
Drizzle ORM + Cloudflare D1 Config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { execSync } from 'node:child_process' | |
import fs from 'node:fs' | |
import path from 'node:path' | |
import { defineConfig } from 'drizzle-kit' | |
const dbName = 'orbitkit-lite-start' | |
/** | |
* Workaround to make drizzle-kit work with local Cloudflare D1 databases. | |
* | |
* Since drizzle-kit doesn't natively understand D1's local development setup, | |
* this function finds or creates the local SQLite file that wrangler manages. | |
* | |
* Enables: drizzle-kit studio, push, generate, migrate commands locally. | |
*/ | |
function getLocalD1DB() { | |
try { | |
const basePath = path.resolve('.wrangler/state/v3/d1') | |
let dbFile = null | |
if (fs.existsSync(basePath)) { | |
dbFile = fs | |
.readdirSync(basePath, { encoding: 'utf-8', recursive: true }) | |
.find((f) => f.endsWith('.sqlite')) | |
} | |
if (!dbFile) { | |
console.log('Creating local D1 database...') | |
execSync(`pnpm wrangler d1 execute ${dbName} --command="select 1"`, { | |
stdio: 'inherit', | |
}) | |
dbFile = fs | |
.readdirSync(basePath, { encoding: 'utf-8', recursive: true }) | |
.find((f) => f.endsWith('.sqlite')) | |
if (!dbFile) { | |
throw new Error('Failed to create local database') | |
} | |
} | |
return path.resolve(basePath, dbFile) | |
} catch (err) { | |
console.error(err) | |
return null | |
} | |
} | |
/** | |
* Drizzle-kit config that works with both local D1 (development) | |
* and remote D1 (production). | |
* | |
* Local: Uses SQLite file via getLocalD1DB() workaround | |
* Production: Uses D1 HTTP API (requires env vars) | |
*/ | |
export default defineConfig({ | |
out: './src/db/migrations', | |
schema: './src/db/schema/index.ts', | |
dialect: 'sqlite', | |
...(process.env.NODE_ENV === 'production' | |
? { | |
driver: 'd1-http', | |
dbCredentials: { | |
accountId: process.env.CLOUDFLARE_ACCOUNT_ID, | |
databaseId: process.env.DATABASE_ID, | |
token: process.env.CLOUDFLARE_API_TOKEN, | |
}, | |
} | |
: { | |
dbCredentials: { | |
url: getLocalD1DB(), | |
}, | |
}), | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment