Skip to content
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

Next.js app build fails when using Prisma with DB driver in Server Action #23600

Open
nzws opened this issue Mar 23, 2024 · 8 comments · May be fixed by #23754
Open

Next.js app build fails when using Prisma with DB driver in Server Action #23600

nzws opened this issue Mar 23, 2024 · 8 comments · May be fixed by #23754
Assignees
Labels
bug/2-confirmed Bug has been reproduced and confirmed. kind/bug A reported bug. team/client Issue for team Client. topic: driverAdapters topic: Next.js

Comments

@nzws
Copy link

nzws commented Mar 23, 2024

Bug description

When building a Next.js application using Prisma on the edge runtime with the Database driver, the build fails with the following error. This problem seems to occur when using Prisma client on the server action imported by the client component. Also, this problem did not occur with Prisma v5.10.2 (in Early Access), and occurred with v5.11.0.

Failed to compile.

app/page.js from Terser
  x await isn't allowed in non-async function
       ,-[26410:1]
 26410 | /* harmony export */ __webpack_require__.d(__webpack_exports__, {
 26411 | /* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
 26412 | /* harmony export */ });
 26413 | /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 9737, 23))).default);
       :                                                                         ^^^^^^^
 26414 | 
 26415 | /***/ }),
       `----

Caused by:
    0: failed to parse input file
    1: Syntax Error
Error: 
  x await isn't allowed in non-async function
       ,-[26410:1]
 26410 | /* harmony export */ __webpack_require__.d(__webpack_exports__, {
 26411 | /* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
 26412 | /* harmony export */ });
 26413 | /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((await Promise.resolve(/* import() */).then(__webpack_require__.t.bind(__webpack_require__, 9737, 23))).default);
       :                                                                         ^^^^^^^
 26414 | 
 26415 | /***/ }),
       `----

Caused by:
    0: failed to parse input file
    1: Syntax Error


> Build failed because of webpack errors

How to reproduce

  1. git clone https://github.com/nzws/prisma-with-nextjs-edge-import-problem-repro
  2. cd prisma-with-nextjs-edge-import-problem-repro
  3. yarn install
  4. yarn build
  5. See error

Expected behavior

The build passes normally and the application can run.

Prisma information

I created a repository that can reproduce this issue: https://github.com/nzws/prisma-with-nextjs-edge-import-problem-repro (nzws/prisma-with-nextjs-edge-import-problem-repro@cc513a7)

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["driverAdapters"]
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}
// ./app/lib/prisma.ts

import { Pool } from "@neondatabase/serverless";
import { PrismaNeon } from "@prisma/adapter-neon";
import { PrismaClient } from "@prisma/client";

export function createPrismaClient() {
  const neon = new Pool({ connectionString: process.env.DATABASE_URL });
  const adapter = new PrismaNeon(neon);
  const prisma = new PrismaClient({ adapter: adapter });

  return prisma;
}
// ./app/actions.ts

"use server";

import { createPrismaClient } from "./lib/prisma";

export async function onCreate() {
  const prisma = createPrismaClient();

  await prisma.user.create({
    data: {
      email: "john@example.com",
      name: "John Doe",
    },
  });
}
// ./app/client-component.tsx: imported by page.tsx

"use client";

import { onCreate } from "./actions";

export function ClientComponent() {
  return (
    <div>
      <h1>Hello, World!</h1>

      <button onClick={onCreate}>Create User</button>
    </div>
  );
}

Environment & setup

  • OS: macOS
  • Database: PostgreSQL
  • Node.js version: v20.10.0

Prisma Version

prisma                  : 5.11.0
@prisma/client          : 5.11.0
Computed binaryTarget   : darwin-arm64
Operating System        : darwin
Architecture            : arm64
Node.js                 : v20.10.0
Query Engine (Node-API) : libquery-engine efd2449663b3d73d637ea1fd226bafbcf45b3102 (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Schema Engine           : schema-engine-cli efd2449663b3d73d637ea1fd226bafbcf45b3102 (at node_modules/@prisma/engines/schema-engine-darwin-arm64)
Schema Wasm             : @prisma/prisma-schema-wasm 5.11.0-15.efd2449663b3d73d637ea1fd226bafbcf45b3102
Default Engines Hash    : efd2449663b3d73d637ea1fd226bafbcf45b3102
Studio                  : 0.499.0
Preview Features        : driverAdapters
@nzws nzws added the kind/bug A reported bug. label Mar 23, 2024
@nzws
Copy link
Author

nzws commented Mar 23, 2024

The top-level await used by the wasm-loader seems to be causing problems. (Probably not officially supported yet: vercel/next.js#31054)

fileMap['wasm-worker-loader.js'] = `export default (await import('./query_engine_bg.wasm')).default`
fileMap['wasm-edge-light-loader.js'] = `export default (await import('./query_engine_bg.wasm?module')).default`

I have not submitted a pull request because I cannot evaluate the impact of this fix, but the build will be succeed if I created the following patch for the Prisma client generator.

diff --git a/generator-build/index.js b/generator-build/index.js
index c66a69ee7783e69352da18aa5f0ac2ee28bc76cd..68b6c11fd61a9c663bdf9aad5359d7a2a4c6a83c 100644
--- a/generator-build/index.js
+++ b/generator-build/index.js
@@ -16644,7 +16644,7 @@ function buildQueryEngineWasmModule(wasm, copyEngine, runtimeNameJs) {
     return `config.engineWasm = {
   getRuntime: () => require('./query_engine_bg.js'),
   getQueryEngineWasmModule: async () => {
-    return (await import('#wasm-engine-loader')).default
+    return (await (await import('#wasm-engine-loader')).default).default
   }
 }`;
   }
@@ -18320,8 +18320,8 @@ async function buildClient({
   if (generator.previewFeatures.includes("driverAdapters")) {
     fileMap["default.js"] = await JS(trampolineTsClient);
     fileMap["default.d.ts"] = await TS(trampolineTsClient);
-    fileMap["wasm-worker-loader.js"] = `export default (await import('./query_engine_bg.wasm')).default`;
-    fileMap["wasm-edge-light-loader.js"] = `export default (await import('./query_engine_bg.wasm?module')).default`;
+    fileMap["wasm-worker-loader.js"] = `export default import('./query_engine_bg.wasm')`;
+    fileMap["wasm-edge-light-loader.js"] = `export default import('./query_engine_bg.wasm?module')`;
     pkgJson["browser"] = "default.js";
     pkgJson["imports"] = {
       // when `import('#wasm-engine-loader')` is called, it will be resolved to the correct file

@WoetDev
Copy link

WoetDev commented Mar 24, 2024

I believe I'm having the same issue when trying to run Prisma + Neon Serverless Driver from the edge runtime, I'm receiving the error:

SyntaxError: Unexpected identifier 'Promise'
    at (action-browser)/./node_modules/.prisma/client/wasm-edge-light-loader.js
    at __webpack_require__

And I think this post on Stackoverflow describes the same issue as well: https://stackoverflow.com/questions/78192413/next-js-application-with-prisma-orm-and-neon-datasource/78213174#78213174

@janpio janpio added topic: Next.js topic: driverAdapters bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. team/client Issue for team Client. labels Mar 25, 2024
@smorimoto
Copy link

Same issue here.

@JWW87
Copy link

JWW87 commented Apr 10, 2024

I have the same issue as well. The proposed fix seems to work well. Can someone review and release this please?

@samtgarson
Copy link

samtgarson commented Apr 19, 2024

I've been receiving this as well, but only when the Edge runtime is enabled in Next.

The fact that this works in the Nodejs runtime (for me), and that other "top level awaits" (unrelated to Prisma) also throw an error when used in the Edge runtime suggests that this is a Next.js issue, rather than a Prisma one?

(although if the patch works, it'd be great to get it in in the meantime)

Edit Can confirm the patch works for me too, and I opened an Issue in Next.js too vercel/next.js#64792

@DannyNemer
Copy link

DannyNemer commented Apr 20, 2024

We are having the same issue using @prisma/client v5.12.1.

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["driverAdapters"]
}
const neon = new Pool({ connectionString: process.env["DATABASE_URL"] });
const adapter = new PrismaNeon(neon);
const prisma = new PrismaClient({ adapter });

When attempting to access the DB from middleware.ts:

 ⚠ ../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/wasm-edge-light-loader.js
The generated code contains 'async/await' because this module is using "topLevelAwait".
However, your target environment does not appear to support 'async/await'.
As a result, the code may not run as expected or may cause runtime errors.

Import trace for requested module:
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/wasm-edge-light-loader.js
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/wasm.js
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/.prisma/client/default.js
../../node_modules/.pnpm/@prisma+client@5.12.1_prisma@5.12.1/node_modules/@prisma/client/default.js
./src/lib/prisma.ts

@vegandiet705
Copy link

Hello, I'm also having this problem since I updated from Next 14.1.4 to 14.2.1. My setup is pretty similar to @DannyNemer . The problem only appears in Edge runtime.

@morgs32
Copy link

morgs32 commented Apr 27, 2024

There's a PR to fix this: #23754

You can resolve it for now by patching @prisma/client. I used pnpm so pnpm patch @prisma/client. Then make these changes: https://github.com/prisma/prisma/pull/23754/files

@jkomyno jkomyno added bug/2-confirmed Bug has been reproduced and confirmed. and removed bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. labels Apr 29, 2024
@Jolg42 Jolg42 assigned jkomyno and unassigned Jolg42 Apr 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug/2-confirmed Bug has been reproduced and confirmed. kind/bug A reported bug. team/client Issue for team Client. topic: driverAdapters topic: Next.js
Projects
None yet
Development

Successfully merging a pull request may close this issue.