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

wasm-edge-light-loader.js importing node:crypto instead of using globalThis.crypto #24415

Closed
p6l-richard opened this issue Jun 4, 2024 · 11 comments
Assignees
Labels
bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. domain/client Issue in the "Client" domain: Prisma Client, Prisma Studio etc. kind/bug A reported bug. topic: driverAdapters topic: Next.js middleware topic: next-auth / Auth.js topic: @prisma/adapter-libsql / Turso

Comments

@p6l-richard
Copy link

p6l-richard commented Jun 4, 2024

Bug description

Problem

When using Prisma in conjunction with NextAuth on the Next.js middleware, you'll see an error from the wasm-edge-light-loader.js as it attempts to import node:crypto.

This requires users currently to split up the NextAuth configuration file to exclude prisma from the configuration that's exported from the next.js middleware file:

// middleware.ts

/**
 * 1️⃣ NextAuth config split 
 * this splits the nextauth config so that we avoid prisma here (works ✅)
 * 
 * Uncomment this block & comment out line xx to see the error go away
 * 
 * */ 
import NextAuth from "next-auth"
import { authConfig as authEdgeConfig } from "./auth/config.edge";
export const { auth: middleware } = NextAuth(authEdgeConfig)

image
image

How to reproduce

  1. gh repo clone p6l-richard/prisma-repro
  2. cd prisma-repro
  3. pnpm i
  4. pnpm run turso (to set up env vars)
  5. pnpm dev
  6. Check the console

Expected behavior

Be able to define Prisma in NextAuth single configuration so that we can import it in the nextjs middleware:

// middleware.ts

/**
 * 2️⃣ Bundled NextAuth config
 * 
 * This includes the prisma adapter in the NextAuth config, which works but throws an error with the wasm-edge-light-loader.js
 */
export {auth as middleware} from "./auth/config";

Prisma information

generator client {
    provider        = "prisma-client-js"
    // This enables turso usage
    previewFeatures = ["driverAdapters"]
}

datasource db {
    provider = "sqlite"
    // NOTE: When using mysql or sqlserver, uncomment the @db.Text annotations in model Account below
    // Further reading:
    // https://next-auth.js.org/adapters/prisma#create-the-prisma-schema
    // https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string
    url      = "file:./dev.db"
}

model User {
    id            String          @id @default(cuid())
    name          String?
    email         String?         @unique
    emailVerified DateTime?
    image         String?
    accounts      Account[]
    sessions      Session[]
    // Optional for WebAuthn support
    Authenticator Authenticator[]

    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
}

model Account {
    id                String  @id @default(cuid())
    userId            String
    type              String
    provider          String
    providerAccountId String
    refresh_token     String?
    access_token      String?
    expires_at        Int?
    token_type        String?
    scope             String?
    id_token          String?
    session_state     String?

    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt

    user User @relation(fields: [userId], references: [id], onDelete: Cascade)

    @@unique([provider, providerAccountId])
}

model Session {
    id           String   @id @default(cuid())
    sessionToken String   @unique
    userId       String
    expires      DateTime
    user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)

    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
}

model VerificationToken {
    identifier String
    token      String
    expires    DateTime

    @@unique([identifier, token])
}

// Optional for WebAuthn support
model Authenticator {
    credentialID         String  @unique
    userId               String
    providerAccountId    String
    credentialPublicKey  String
    counter              Int
    credentialDeviceType String
    credentialBackedUp   Boolean
    transports           String?

    user User @relation(fields: [userId], references: [id], onDelete: Cascade)

    @@id([userId, credentialID])
}
import { createClient } from "@libsql/client";
import { PrismaLibSQL } from "@prisma/adapter-libsql";
import { PrismaClient } from "@prisma/client";

if (!process.env.TURSO_DATABASE_URL && !process.env.TURSO_AUTH_TOKEN) {
  throw new Error("TURSO_DATABASE_URL and TURSO_AUTH_TOKEN must be set in the environment. You can run `pnpm turso` to the this up for you.");
}

const libsql = createClient({
  url: `${process.env.TURSO_DATABASE_URL}`,
  authToken: `${process.env.TURSO_AUTH_TOKEN}`,
});

const adapter = new PrismaLibSQL(libsql);

const createPrismaClient = () =>
  new PrismaClient({
    adapter,
    log: process.env.NODE_ENV === "development" ? ["query", "error", "warn"] : ["error"],
  });

const globalForPrisma = globalThis as unknown as {
  prisma: ReturnType<typeof createPrismaClient> | undefined;
};

export const db = globalForPrisma.prisma ?? createPrismaClient();

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = db;

Environment & setup

  • OS: macOS
  • Database: Turso
  • Node.js version: v20.14.0

Prisma Version


@p6l-richard p6l-richard added the kind/bug A reported bug. label Jun 4, 2024
@janpio janpio added topic: next-auth / Auth.js topic: Next.js middleware topic: driverAdapters bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. domain/client Issue in the "Client" domain: Prisma Client, Prisma Studio etc. labels Jun 4, 2024
@jkomyno
Copy link
Contributor

jkomyno commented Jun 4, 2024

This seems connected to #24386, which was opened 2 days ago. This makes me think that this problem is not connected to today's release, Prisma 5.15.0.

Thanks for the reproduction, we'll take a look and investigate why this issue is happening. Thanks!

@janpio
Copy link
Contributor

janpio commented Jun 4, 2024

(Reproduction is also still using 5.14.0, so safe to say not related to today's 5.15.0)

@janpio
Copy link
Contributor

janpio commented Jun 5, 2024

Hey @p6l-richard, gave this a quick shot:

  1. The pnpm turso command does not actually exist, but thankfully the credentials are not really needed and I could just put a temporary .env file that did the job of unblocking:
    AUTH_SECRET="just an example"
    TURSO_DATABASE_URL="libsql://foo.turso.io"
    TURSO_AUTH_TOKEN="eyJhbG..."
    
  2. With the provided [email protected] I run into this warning:
     ⚠ ./node_modules/.pnpm/@[email protected][email protected]/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/@[email protected][email protected]/node_modules/.prisma/client/wasm-edge-light-loader.js
    ./node_modules/.pnpm/@[email protected][email protected]/node_modules/.prisma/client/wasm.js
    ./node_modules/.pnpm/@[email protected][email protected]/node_modules/.prisma/client/default.js
    ./node_modules/.pnpm/@[email protected][email protected]/node_modules/@prisma/client/default.js
    ./prisma/client.ts
    ./auth/config.ts
    
  3. After upgrading to 5.15.0, because we fixed that bug in this release, I now get this error:
    ✓ Compiled in 458ms (985 modules)
     ⨯ auth/config.ts (19:12) @ <unknown>
     ⨯ (0 , react__WEBPACK_IMPORTED_MODULE_2__.cache) is not a function
      17 |   });
      18 |
    > 19 |     export const auth = cache(async () => {
         |            ^
      20 |         try {
      21 |           return await uncachedAuth();
      22 |         } catch (err) {
    

Am I missing something?
I noticed your screenshot say Next.js (14.2.1-canary.3) for example - is the project maybe using the wrong dependency?

@p6l-richard
Copy link
Author

Hey @p6l-richard, gave this a quick shot:

  1. The pnpm turso command does not actually exist, but thankfully the credentials are not really needed and I could just put a temporary .env file that did the job of unblocking:

 AUTH_SECRET="just an example"

 TURSO_DATABASE_URL="libsql://foo.turso.io"

 TURSO_AUTH_TOKEN="eyJhbG..."

Oh great catch, it was named "" - I've updated it. Thanks for pointing this out and good to see that the copy of env.example did the trick.

p6l-richard/prisma-repro@8e8d030

Re: package versions
Another good point, thanks for bringing this to my attention.

It is possible that there's a drift between releases somehow. However, I merely ran npx create-next-app & pnpm add prisma yesterday (didn't specify the versions manually), which makes me wonder why I'd get outdated Prisma version. 🤔

Anyways, I'll take a look later and cycle back.

@jkomyno
Copy link
Contributor

jkomyno commented Jun 5, 2024

✓ Compiled in 458ms (985 modules)
⨯ auth/config.ts (19:12) @
⨯ (0 , react__WEBPACK_IMPORTED_MODULE_2__.cache) is not a function
17 | });
18 |

19 | export const auth = cache(async () => {
| ^
20 | try {
21 | return await uncachedAuth();
22 | } catch (err) {

I've also attempted a reproduction.
About (3), one can get rid of (0 , react__WEBPACK_IMPORTED_MODULE_2__.cache) is not a function by simply removing the usage of cache in https://github.com/p6l-richard/prisma-repro/blob/b66e9a72051c98769f071e73ea997758898c966b/auth/config.ts.

After doing that - and updating prisma* to 5.15.0, I see no errors at all, so I can't reproduce the node:crypto problem.

@janpio
Copy link
Contributor

janpio commented Jun 5, 2024

which makes me wonder why I'd get outdated Prisma version. 🤔

You didn't, we just released Prisma 5.15.0 yesterday 😆
But the Next.js version mismatch is weird and interesting.

About (3), one can get rid of (0 , react__WEBPACK_IMPORTED_MODULE_2__.cache) is not a function by simply removing the usage of cache in p6l-richard/prisma-repro@b66e9a7/auth/config.ts.

Good catch @jkomyno, I can confirm that.

So optimally you update all the versions @p6l-richard and then update your reproduction.

@janpio
Copy link
Contributor

janpio commented Jun 5, 2024

Oh by the way: We do have another bug report that mentions node:crypto as well in the context of Prisma driver adapters, but that is only when trying to use pg (via @prisma/adapter-pg) in a Next.js middleware - so that does not apply to your usage of Turso or LibSQL :/

(It is a bug in pg itself that applies generally to usage in Next.js middleware. You can read more here: #24430 + brianc/node-postgres#3206)

@p6l-richard
Copy link
Author

This is interesting. I just deleted node_modules & .next cache and ran a fresh pnpm i again (with the @prisma/client at 15.5.0).

I now get a module resolution error for the prisma client:
CleanShot 2024-06-05 at 16 04 35@2x

@janpio
Copy link
Contributor

janpio commented Jun 5, 2024

(We figured out via another channel that this Can't resolve problem was caused by the package manager)

@p6l-richard
Copy link
Author

So the issue remaining seems to be the module resolution error on Next.js 14.2.3 as cache() seems to be undefined as pointed out by @jkomyno.

@janpio
Copy link
Contributor

janpio commented Jun 5, 2024

Closing the issue here then, as Prisma works as expected. Good luck figuring out the rest 🤞

@janpio janpio closed this as not planned Won't fix, can't repro, duplicate, stale Jun 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug/1-unconfirmed Bug should have enough information for reproduction, but confirmation has not happened yet. domain/client Issue in the "Client" domain: Prisma Client, Prisma Studio etc. kind/bug A reported bug. topic: driverAdapters topic: Next.js middleware topic: next-auth / Auth.js topic: @prisma/adapter-libsql / Turso
Projects
None yet
Development

No branches or pull requests

3 participants