Skip to content

fix(runtime): use dynamic import for #content/adapter to prevent prerender failure - #3830

Open
gepotumu wants to merge 2 commits into
nuxt:mainfrom
gepotumu:fix/lazy-adapter-import-prerender
Open

fix(runtime): use dynamic import for #content/adapter to prevent prerender failure#3830
gepotumu wants to merge 2 commits into
nuxt:mainfrom
gepotumu:fix/lazy-adapter-import-prerender

Conversation

@gepotumu

@gepotumu gepotumu commented Aug 9, 2026

Copy link
Copy Markdown

Summary

Fixes #3829

When sqliteConnector: 'bun' is configured and the build runs on Node.js (e.g. nuxt build --preset bun), the prerender stage fails with:

ERROR  Only URLs with a scheme in: file, data, and node are supported by the default ESM loader.
Received protocol 'bun:'

Root Cause

database.server.ts uses a static top-level import for #content/adapter:

import adapter from '#content/adapter'   // ← static, resolved at module load time

Node.js ESM loader resolves ALL static imports at module load time, regardless of whether the imported binding is actually called. During prerender, only localAdapter is used (line 18), but the static import forces Node.js to resolve bun:sqlite — which fails because bun: is not a valid Node.js URL scheme.

Fix

Replace the static import with a lazy dynamic import() that is only resolved in the production code path:

let _adapterPromise: Promise<(opts: unknown) => Connector> | undefined

function getAdapter(): Promise<(opts: unknown) => Connector> {
  if (!_adapterPromise) {
    _adapterPromise = import('#content/adapter').then(m => m.default || m)
  }
  return _adapterPromise
}

This makes loadDatabaseAdapter async — a minimal API change since all callers (query.post.ts event handler and _checkAndImportDatabaseIntegrity) already operate in async contexts.

Why This Works

Stage Before After
Module load Static import → Node.js resolves bun:sqliteERROR Only imports localAdapter (Node.js-compatible) → ✅
Prerender runtime Uses localAdapter Uses localAdapter (unchanged)
Production runtime Uses adapter await getAdapter() → dynamic import → works in Bun

Changes

  • src/runtime/internal/database.server.ts — Remove static import of #content/adapter, add lazy getAdapter(), make loadDatabaseAdapter async
  • src/runtime/api/query.post.ts — Await the now-async loadDatabaseAdapter
  • Added regression test and test mock infrastructure

Test Plan

  • Unit test: source does NOT contain static top-level import of #content/adapter
  • Unit test: loadDatabaseAdapter returns a working DatabaseAdapter via dynamic import
  • Unit test: production path uses adapter, adapter is cached across calls
  • Existing 246 unit tests pass
  • Full Nuxt build with content module succeeds (prerender included)

Made with Cursor

…erender failure

When `sqliteConnector: 'bun'` is configured and the build runs on Node.js,
the prerender stage fails because Node.js cannot resolve the `bun:` protocol.

Root cause: `database.server.ts` used a static top-level import for
`#content/adapter`. Node.js ESM loader resolves all static imports at
module load time, regardless of whether the binding is called at runtime.
During prerender only `localAdapter` is used, but the static import of
`adapter` still forces resolution of `bun:sqlite`.

Fix: Replace the static import with a lazy dynamic `import()` that is
only resolved in the production code path (non-prerender, non-dev).
This makes `loadDatabaseAdapter` async, which is a minimal API change
since all callers already operate in async contexts.

Closes nuxt#3829

Co-authored-by: Cursor <cursoragent@cursor.com>
@vercel

vercel Bot commented Aug 9, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the Nuxt Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 939532dc-e821-445d-b91a-cf70de1a5964

📥 Commits

Reviewing files that changed from the base of the PR and between c6c19fb and ea90e4b.

📒 Files selected for processing (3)
  • test/mock/content-adapter.ts
  • test/mock/content-local-adapter.ts
  • test/unit/database.server.prerender.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/mock/content-local-adapter.ts
  • test/mock/content-adapter.ts
  • test/unit/database.server.prerender.test.ts

📝 Walkthrough

Walkthrough

The runtime now loads the production database adapter through a cached dynamic import. loadDatabaseAdapter is asynchronous, and its callers await the result. Development and prerender environments continue using the local adapter. Tests add adapter mocks, manifest data, Vitest aliases, and regression coverage for dynamic loading, caching, database methods, and query results.

Estimated code review effort: 3 (Moderate) | ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the dynamic import fix that prevents prerender failures.
Description check ✅ Passed The description explains the prerender failure, root cause, dynamic import fix, affected callers, and validation results.
Linked Issues check ✅ Passed The changes address issue #3829 by lazily loading the Bun adapter, preserving the local prerender adapter, and retaining production adapter behavior.
Out of Scope Changes check ✅ Passed All changes support the dynamic adapter loading fix, including caller updates, test mocks, aliases, and regression tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/internal/database.server.ts`:
- Around line 24-30: Update the connector initialization flow around the
module-level db guard and getAdapter so concurrent first calls share a cached
initialization promise, ensuring the adapter factory runs only once and all
callers receive the same connector. Preserve the existing dev/localAdapter and
production adapter selection behavior, and add a Promise.all regression test
covering concurrent initial calls.

In `@test/mock/content-adapter.ts`:
- Line 3: Rename the unused prepare callback parameter from sql to _sql in
test/mock/content-adapter.ts:3-3, test/mock/content-local-adapter.ts:3-3, and
each affected callback in test/unit/database.server.prerender.test.ts:48-48,
57-57, and 87-87, while preserving the mock interface and callback behavior.

In `@test/unit/database.server.prerender.test.ts`:
- Line 75: Replace the `config as any` casts in
`test/unit/database.server.prerender.test.ts` at lines 75, 109, and 113 with one
shared fixture typed as `RuntimeConfig['content']`, and pass that fixture
directly to `loadDatabaseAdapter` at each site.
- Around line 31-42: The static import assertion using staticImportPattern must
reject every top-level `#content/adapter` import form, including named, namespace,
side-effect, and combined imports, while continuing to allow dynamic
import('`#content/adapter`'). Replace the regex-only check with an import parser
or parser-backed assertion that distinguishes static imports from dynamic
imports.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 21366656-2258-4171-b08b-41890e02e463

📥 Commits

Reviewing files that changed from the base of the PR and between dc90e96 and c6c19fb.

📒 Files selected for processing (7)
  • src/runtime/api/query.post.ts
  • src/runtime/internal/database.server.ts
  • test/mock/content-adapter.ts
  • test/mock/content-local-adapter.ts
  • test/mock/content-manifest.ts
  • test/unit/database.server.prerender.test.ts
  • vitest.config.ts

Comment on lines 24 to 30
if (!db) {
if (import.meta.dev || ['nitro-prerender', 'nitro-dev'].includes(import.meta.preset as string)) {
db = localAdapter(refineDatabaseConfig(localDatabase))
}
else {
const adapter = await getAdapter()
db = adapter(refineDatabaseConfig(database))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Make connector initialization atomic.

Concurrent production requests can both pass if (!db) before either resumes from await getAdapter(). Both requests then call the adapter factory. One connector is discarded when the later assignment overwrites db.

Cache the connector initialization promise, not only the module import. Add a Promise.all regression test for concurrent first calls.

Proposed fix
 let db: Connector
 let _adapterPromise: Promise<(opts: unknown) => Connector> | undefined
+let _databasePromise: Promise<Connector> | undefined

 export default async function loadDatabaseAdapter(config: RuntimeConfig['content']) {
   const { database, localDatabase } = config

   if (!db) {
-    if (import.meta.dev || ['nitro-prerender', 'nitro-dev'].includes(import.meta.preset as string)) {
-      db = localAdapter(refineDatabaseConfig(localDatabase))
-    }
-    else {
-      const adapter = await getAdapter()
-      db = adapter(refineDatabaseConfig(database))
+    if (!_databasePromise) {
+      _databasePromise = (async () => {
+        if (import.meta.dev || ['nitro-prerender', 'nitro-dev'].includes(import.meta.preset as string)) {
+          return localAdapter(refineDatabaseConfig(localDatabase))
+        }
+        const adapter = await getAdapter()
+        return adapter(refineDatabaseConfig(database))
+      })()
     }
+    db = await _databasePromise
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/runtime/internal/database.server.ts` around lines 24 - 30, Update the
connector initialization flow around the module-level db guard and getAdapter so
concurrent first calls share a cached initialization promise, ensuring the
adapter factory runs only once and all callers receive the same connector.
Preserve the existing dev/localAdapter and production adapter selection
behavior, and add a Promise.all regression test covering concurrent initial
calls.

Comment thread test/mock/content-adapter.ts Outdated
Comment on lines +31 to +42
// Should NOT have a static import statement for #content/adapter
const staticImportPattern = /^import\s+\w+\s+from\s+['"]#content\/adapter['"]/m
expect(source).not.toMatch(staticImportPattern)

// Should still have the local-adapter static import (that one is fine,
// it resolves to a Node.js-compatible connector)
const localAdapterPattern = /^import\s+\w+\s+from\s+['"]#content\/local-adapter['"]/m
expect(source).toMatch(localAdapterPattern)

// Should have a dynamic import of #content/adapter
const dynamicImportPattern = /import\(['"]#content\/adapter['"]\)/
expect(source).toMatch(dynamicImportPattern)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file list candidates =="
fd -a 'database.server.prerender.test.ts' . || true

echo "== target file excerpt =="
file="$(fd 'database.server.prerender.test.ts' . | head -n1 || true)"
if [ -n "$file" ]; then
  nl -ba "$file" | sed -n '1,120p'
fi

echo "== related patterns in file =="
if [ -n "$file" ]; then
  rg -n "staticImportPattern|localAdapterPattern|dynamicImportPattern|content/adapter|content/local-adapter|describe|test|expect" "$file" || true
fi

echo "== repo search for adapter imports in tests/code =="
rg -n "from\\s+['\"]`#content/adapter`['\"]|from\\s+['\"]`#content/local-adapter`['\"]|import\\(\\s*['\"]`#content/adapter`['\"]\\s*\\)" . || true

Repository: nuxt/content

Length of output: 307


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="$(fd 'database.server.prerender.test.ts' . | head -n1)"
echo "== target file excerpt =="
awk '{printf "%7d  %s\n", NR, $0}' "$FILE" | sed -n '1,140p'

echo "== related patterns in file =="
rg -n "staticImportPattern|localAdapterPattern|dynamicImportPattern|content/adapter|content/local-adapter|describe|test\\(|expect" "$FILE" || true

echo "== repo search for adapter import strings =="
rg -n "from\\s+['\"]`#content/adapter`['\"]|from\\s+['\"]`#content/local-adapter`['\"]|import\\(?\\s*['\"]`#content/adapter`['\"]\\s*\\)?|`#content/adapter`" . || true

Repository: nuxt/content

Length of output: 9054


🌐 Web query:

MDN JavaScript import statements default import named import namespace import side effect import regex

💡 Result:

In JavaScript, import statements are used to access exported functionality from modules [1]. These declarations are hoisted, meaning they are evaluated before the rest of the module's code [1][2]. The primary types of static import syntax include: Default Import: Imports the default export of a module [1]. The identifier can be named arbitrarily [1][2]. import defaultExport from "module-name"; Named Import: Imports specific named exports from a module [1]. These can be aliased using the as keyword [1][2]. import { export1, export2 as alias2 } from "module-name"; Namespace Import: Imports all exports from a module into a single object, which acts as a namespace [1][2]. import * as name from "module-name"; Side Effect Import: Executes the module's top-level code without importing any specific values [1]. import "module-name"; Note: It is also possible to combine these forms, such as importing a default along with named or namespace imports [1]. Regarding Regular Expressions: Parsing JavaScript import statements with regular expressions is notoriously difficult due to the complexity of the grammar, such as handling multiline statements, varied whitespace, comments, and different quoting styles [3][4]. While basic patterns can be crafted for simple cases, official documentation recommends against using regex to parse code [3][4]. If you require precise matching for tooling or analysis, it is standard practice to use an established parser or a library designed for this purpose (such as those that leverage Babel or other AST-based tools) rather than custom regex patterns [4]. Community-maintained packages exist for this specific purpose if AST parsing is not feasible [4].

Citations:


Detect every static #content/adapter import form.

staticImportPattern only matches default imports such as import adapter from '#content/adapter'. Named imports, namespace imports, side-effect imports, and combined import lists for #content/adapter are also static top-level imports, and Node.js would resolve the Bun-only module at load time. Use an import parser or a parser-backed assertion that rejects all static #content/adapter imports while allowing import('#content/adapter').

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit/database.server.prerender.test.ts` around lines 31 - 42, The static
import assertion using staticImportPattern must reject every top-level
`#content/adapter` import form, including named, namespace, side-effect, and
combined imports, while continuing to allow dynamic import('`#content/adapter`').
Replace the regex-only check with an import parser or parser-backed assertion
that distinguishes static imports from dynamic imports.

Comment thread test/unit/database.server.prerender.test.ts Outdated
- Prefix unused parameters with `_` to satisfy @typescript-eslint/no-unused-vars
- Replace `as any` casts with a shared typed config fixture
- Remove unused variable assignment

Co-authored-by: Cursor <cursoragent@cursor.com>
@pkg-pr-new

pkg-pr-new Bot commented Aug 10, 2026

Copy link
Copy Markdown
npm i https://pkg.pr.new/@nuxt/content@3830

commit: ea90e4b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sqliteConnector: 'bun' fails during prerender when building on Node.js for Bun deployment

1 participant