Skip to content

[BUG] @prisma/client + @prisma/adapter-d1 do not work in OpenNext middleware #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Juuldamen opened this issue Mar 18, 2025 · 9 comments
Closed
Labels
bug Something isn't working triage

Comments

@Juuldamen
Copy link
Contributor

Juuldamen commented Mar 18, 2025

Describe the bug

Hi.

I've been trying out migrating an app from next-on-pages to open-next. The app uses D1 through the @prisma/client + @prisma/adapter-d1 dependencies. The initialization of the database is done in the Next.js middleware. Very similar to https://developers.cloudflare.com/d1/tutorials/d1-and-prisma-orm/.

When I try to run the app with opennextjs-cloudflare && wrangler dev this results in a build error.

OpenNext build complete.

 ⛅️ wrangler 4.0.0 (update available 4.1.0)
-----------------------------------------------------

Your Worker and resources are simulated locally via Miniflare. For more information, see: https://developers.cloudflare.com/workers/testing/local-development.

Your worker has access to the following bindings:
- D1 Databases:
  - DB: OPENNEXT_TEST_DB (<insert-database-id>) [simulated locally]
[wrangler:inf] Ready on http://localhost:8787

✘ [ERROR] Build failed with 1 error:

  ✘ [ERROR] ENOENT: no such file or directory, open
  '/home/username/opennext-middleware-wasm-issue/.open-next/middleware/wasm/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm'
  [plugin wrangler-module-collector]

      node_modules/esbuild/lib/main.js:1226:21:
        1226 │         let result = await callback({
             ╵                      ^

      at async open (node:internal/fs/promises:638:25)
      at async readFile (node:internal/fs/promises:1242:14)
      at async
  /home/username/opennext-middleware-wasm-issue/node_modules/wrangler/wrangler-dist/cli.js:91690:37

Looking at the generated middleware file in .open-next/middleware/handler.mjs I can see that a .wasm file is imported import wasm_ea010aa52414c7de383495546f15cb7d49b055fc2 from "./wasm/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm";. This wasm file is used by Prisma client, it is not included when Prisma is removed.

The wasm file is included in the Next.js build artifacts at .next/server/edge-chunks/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm. And it is also included in
.next/server/middleware-manifest.json. But it is not copied over to .open-next/middleware/wasm like the above import expects.

Looking at the code in opennextjs-aws that handles this, the wasm files are indeed not copied.
https://github.dev/opennextjs/opennextjs-aws/blob/dd3a610d98f2a414c091d26968e91eca21f76dd6/packages/open-next/src/build/createMiddleware.ts#L66

There is code elsewhere that copies the wasm files, but this does not apply to the middleware configured in my repo.
https://github.dev/opennextjs/opennextjs-aws/blob/dd3a610d98f2a414c091d26968e91eca21f76dd6/packages/open-next/src/build/edge/createEdgeBundle.ts#L202

When I manually copy over the wasm file to .open-next/middleware/wasm/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm, run npx wrangler dev and visit http://localhost:8787/ the initial error is resolved. But it is replaced by a different error:

[wrangler:inf] Ready on http://localhost:8787
⎔ Starting local server...
middleware
[wrangler:err] ReferenceError: wasm_ea010aa52414c7de383495546f15cb7d49b055fc is not defined
    at 938 (file:///home/username/opennext-middleware-wasm-issue/.open-next/middleware/handler.mjs:1625:19)
    at t (file:///home/username/opennext-middleware-wasm-issue/.open-next/middleware/handler.mjs:367:14)
    at y.t (file:///home/username/opennext-middleware-wasm-issue/.open-next/middleware/handler.mjs:397:29)

This error makes sense because for a peculiar reason the wasm default import name has a 2 suffixed to it that is not expected when it is later exported.

// .open-next/middleware/handler.mjs
import wasm_ea010aa52414c7de383495546f15cb7d49b055fc2 from "./wasm/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm";

// The below does not contain the suffixed 2 in the name
}, 938: (e) => {
   e.exports = wasm_ea010aa52414c7de383495546f15cb7d49b055fc;
}, 671: (e, t, r) => {

I debugged the code that writes this import based on the data from middleware-manifest.json, and here the name does not include the 2 suffix. So I assume it is ESBuild or another part of OpenNext making changes to this import later in the build process.

I see that other people have also encountered issues using Prisma in the past, but with different errors: #139. That's why I created a separate issue for this one.

I can create a PR to copy the .wasm files for this middleware configuration. But I lack context what might be needed for other configurations. So any insight here is appreciated.

Steps to reproduce

  1. Clone https://github.com/Juuldamen/opennext-middleware-wasm-issue (sorry StackBlitz doesn't seem to play nice with Next.js)
  2. npm install
  3. npm run preview

Expected behavior

wrangler dev and wrangler deploy build successfully when using @prisma/client + @prisma/adapter-d1 in external middleware. And localhost:8787/ can be visited without runtime errors.

@opennextjs/cloudflare version

0.5.12

Wrangler version

4.0.0

next info output

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP Tue Nov 5 00:21:55 UTC 2024
  Available memory (MB): 48179
  Available CPU cores: 16
Binaries:
  Node: 22.14.0
  npm: 10.9.2
  Yarn: 1.22.22
  pnpm: N/A
Relevant Packages:
  next: 14.2.24 // An outdated version detected (latest is 15.2.3), upgrade is highly recommended!
  eslint-config-next: 14.2.24
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.8.2
Next.js Config:
  output: N/A
 ⚠ An outdated version detected (latest is 15.2.3), upgrade is highly recommended!
   Please try the latest canary version (`npm install next@canary`) to confirm the issue still exists before creating a new issue.
   Read more - https://nextjs.org/docs/messages/opening-an-issue

Additional context

No response

@Juuldamen Juuldamen added bug Something isn't working triage labels Mar 18, 2025
@lixinyang123
Copy link

I'm having same issue

@Juuldamen
Copy link
Contributor Author

I've updated the reproduction repository to 0.6.2. The issue still occurs.

user: ~/opennext-middleware-wasm-issue$ npm run preview

> [email protected] preview
> opennextjs-cloudflare build && opennextjs-cloudflare preview


┌─────────────────────────────┐
│ OpenNext — Cloudflare build │
└─────────────────────────────┘

App directory: /home/user/opennext-middleware-wasm-issue
Next.js version : 14.2.26
@opennextjs/cloudflare version: 0.6.2
@opennextjs/aws version: https://pkg.pr.new/@opennextjs/aws@798

┌─────────────────────────────────┐
│ OpenNext — Building Next.js app │
└─────────────────────────────────┘


> [email protected] build
> npm run generate-db-types && next build


> [email protected] generate-db-types
> prisma generate --schema=./src/schema.prisma

Prisma schema loaded from src/schema.prisma

✔ Generated Prisma Client (v6.5.0) to ./node_modules/@prisma/client in 40ms

Start by importing your Prisma Client (See: https://pris.ly/d/importing-client)

Tip: Want to react to database changes in your app as they happen? Discover how with Pulse: https://pris.ly/tip-1-pulse

  ▲ Next.js 14.2.26

   Creating an optimized production build ...
 ⚠ Compiled with warnings

./node_modules/@prisma/adapter-d1/dist/index.mjs
A Node.js API is used (process.stdout at line: 19) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/@prisma/adapter-d1/dist/index.mjs

./node_modules/@prisma/adapter-d1/dist/index.mjs
A Node.js API is used (process.stdout at line: 19) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/@prisma/adapter-d1/dist/index.mjs

./node_modules/@prisma/debug/dist/index.mjs
A Node.js API is used (process.stdout at line: 45) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/@prisma/debug/dist/index.mjs
./node_modules/@prisma/driver-adapter-utils/dist/index.mjs
./node_modules/@prisma/adapter-d1/dist/index.mjs

./node_modules/@prisma/debug/dist/index.mjs
A Node.js API is used (process.stdout at line: 45) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

Import trace for requested module:
./node_modules/@prisma/debug/dist/index.mjs
./node_modules/@prisma/driver-adapter-utils/dist/index.mjs
./node_modules/@prisma/adapter-d1/dist/index.mjs

 ✓ Compiled successfully
 ✓ Linting and checking validity of types
 ✓ Collecting page data
 ✓ Generating static pages (5/5)
 ✓ Collecting build traces
 ✓ Finalizing page optimization

Route (app)                              Size     First Load JS
┌ ○ /                                    5.47 kB        92.6 kB
└ ○ /_not-found                          873 B            88 kB
+ First Load JS shared by all            87.1 kB
  ├ chunks/117-6a1a8491484a9c3b.js       31.6 kB
  ├ chunks/fd9d1056-749e5812300142af.js  53.6 kB
  └ other shared chunks (total)          1.87 kB


ƒ Middleware                             74.9 kB

○  (Static)  prerendered as static content


┌──────────────────────────────┐
│ OpenNext — Generating bundle │
└──────────────────────────────┘

Bundling middleware function...
Bundling static assets...
Bundling cache assets...
Building server function: default...
Applying code patches: 856.274ms
# copyPackageTemplateFiles
⚙️ Bundling the OpenNext server...

✘ [ERROR] Could not resolve "./wasm/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm"

    .open-next/server-functions/default/middleware.mjs:6752:59:
      6752 │ ..._ea010aa52414c7de383495546f15cb7d49b055fc2 from "./wasm/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm";~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:1476
  let error = new Error(text);
              ^

Error: Build failed with 1 error:
.open-next/server-functions/default/middleware.mjs:6752:59: ERROR: Could not resolve "./wasm/wasm_ea010aa52414c7de383495546f15cb7d49b055fc.wasm"
    at failureErrorWithLog (/home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:1476:15)
    at /home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:945:25
    at runOnEndCallbacks (/home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:1316:45)
    at buildResponseToResult (/home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:943:7)
    at /home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:970:16
    at responseCallbacks.<computed> (/home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:622:9)
    at handleIncomingPacket (/home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:677:12)
    at Socket.readFromStdout (/home/user/opennext-middleware-wasm-issue/node_modules/esbuild/lib/main.js:600:7)
    at Socket.emit (node:events:518:28)
    at addChunk (node:internal/streams/readable:561:12) {
  errors: [Getter/Setter],
  warnings: [Getter/Setter]
}

Node.js v22.14.0

@vicb
Copy link
Contributor

vicb commented Mar 27, 2025

I made some progress here but I hit

Image

So I guess the repro steps you indicated above are not everything needed. Do you have any idea on how to init the DB?

(What I did is similar to what you mention: copy the wasm files, make sure the name matches what's in the manifest)

@Juuldamen
Copy link
Contributor Author

Thanks for taking a look @vicb 😃

I've updated the repo with instructions + @opennextjs/cloudflare 0.6.3

  1. npx wrangler d1 create <insert-db-name>.
    • I have not found a way to create a D1 database only for local use with Wrangler. I assume you have a Cloudflare account that can create a remote D1 database?
  2. Add config for the D1 database in wrangler.jsonc:
	"d1_databases": [
		{
			"binding": "DB",
			"database_name": "<insert-database-name>",
			"database_id": "<insert-database-id>",
			"migrations_dir": "./migrations"
		}
	]
  1. npm run generate-db-types.
    • This will generate the Prisma JavaScript client in node_modules based on src/schema.prisma.
  2. npm run dev and visit localhost:3000.
    • This should generate the local D1 .sqlite files at /opennext-middleware-wasm-issue/.wrangler/state/v3/d1/miniflare-D1DatabaseObject. You can ignore the errors when visiting localhost:3000.
  3. npx wrangler d1 migrations create <insert-database-name> create_tables
  4. npx prisma migrate diff --from-local-d1 --to-schema-datamodel ./src/schema.prisma --script --output ./migrations/0001_create_tables.sql.
    • Generates migration script to create the initial tables with Prisma
  5. npx wrangler d1 migrations apply <insert-database-name>
    • Tables should now be create in local D1 database

After that the database schema should be there without any populated data. Which should be enough to test the await db['account'].findMany(); query in middleware.ts with npm run preview.

@vicb
Copy link
Contributor

vicb commented Mar 29, 2025

@Juuldamen can you give it a try with the latest release? wasm should work now. Please report!

@opennextjs opennextjs deleted a comment from tomocrafter Mar 29, 2025
@vicb
Copy link
Contributor

vicb commented Mar 29, 2025

@tomocrafter I deleted your message because it looks like a different issue. Also there is nothing we can really do without a proper repro. Please open different issue linking a GH repo with a minimal repro.

@tomocrafter
Copy link

@vicb Thank you, I'll create repro and make new issue.

@Juuldamen
Copy link
Contributor Author

@vicb I've tested the new version in the repro repository and it it works there. Thanks very much 😄. I will test in the actual app I'm working on in the coming days. To see if the more complex use case with Prisma hits any other snags.

@vicb
Copy link
Contributor

vicb commented Mar 31, 2025

Thanks for reporting @Juuldamen.

I'm closing this issue then.

@vicb vicb closed this as completed Mar 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working triage
Projects
None yet
Development

No branches or pull requests

4 participants