Skip to content

[v1] D1 binding accessed at module load time, breaks Cloudflare Workers deploy #692

@onmax

Description

@onmax

I know this is a nightly version and that the changes are not ready for public scrutiny, but I thought it might be helpful. ;)

When deploying to Cloudflare Workers, the generated hub:db module for D1 fails with:
Uncaught Error: DB binding not found

The issue is in the generated .nuxt/hub/db.mjs:

const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB
const db = drizzle(binding, { schema })

This runs at module load time. On Cloudflare Workers, D1 bindings are only available within request context, not during module initialization.

Repro: Any code that imports hub:db at module load time (via middleware or server utils that are imported by middleware).

Expected: D1 binding access should be lazy - only when actually querying the database.

Workaround: Is there a recommended pattern to access D1 lazily in v1? Currently we're using:

Details

diff --git a/dist/module.mjs b/dist/module.mjs
index 568a901855a52514a111c80e6225fd583076f997..925a5700fa25765126a98d17058a45e7bd48a161 100644
--- a/dist/module.mjs
+++ b/dist/module.mjs
@@ -268,14 +268,20 @@ export { db, schema }
 `;
   }
   if (driver === "d1") {
+    // PATCHED: Lazy D1 binding access - see https://github.com/nuxt-hub/core/issues/692
     drizzleOrmContent = `import { drizzle } from 'drizzle-orm/d1'
 import * as schema from './db/schema.mjs'

-const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB
-if (!binding && !import.meta.prerender) {
-  throw new Error('DB binding not found')
+let _db
+function getDb() {
+  if (!_db) {
+    const binding = process.env.DB || globalThis.__env__?.DB || globalThis.DB
+    if (!binding) throw new Error('DB binding not found')
+    _db = drizzle(binding, { schema })
+  }
+  return _db
 }
-const db = drizzle(binding, { schema })
+const db = new Proxy({}, { get(_, prop) { return getDb()[prop] } })
 export { db, schema }
 `;
   }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions