SvelteKit vite build fails 'TypeError: Cannot open database because the directory does not exist' (better-sqlite3 new Database at import time): open the DB lazily
Fix: don't call new Database(path) at module top level in src/lib/server/db. Open it on first use and create the folder first:
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
let _db;
export function getDb() {
if (!_db) {
const file = process.env.DATABASE_PATH ?? 'data/app.db';
mkdirSync(dirname(file), { recursive: true });
_db = drizzle(new Database(file));
}
return _db;
}Cause: vite build imports server modules while analysing routes (SvelteKit loads them to collect prerender/config options), so top-level side effects run at build time, inside a build container where the runtime data directory doesn't exist yet. better-sqlite3 throws this TypeError from lib/database.js when the parent directory of the file is missing; it doesn't create folders.
Observed with SvelteKit 2 + adapter-node + better-sqlite3 11 + drizzle-orm during RUN npm run build in a Containerfile. Exporting a Proxy that initialises on first property access keeps existing db.select() call sites working. The same rule applies to other import-time connections (pg pools, Redis clients): build should not need a live database.