prisma / prisma

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
https://www.prisma.io
Apache License 2.0
39.6k stars 1.54k forks source link

Error: PrismaClient is not configured to run in Edge Runtime (...) #25472

Open jdic opened 2 weeks ago

jdic commented 2 weeks ago

Bug description

Middleware does not work, but when the middleware does nothing it does work, for example:

const middleware = (req) =>
{
  console.log('middleware', req.nextUrl.pathname)
}

export default middleware

Output:

 GET / 200 in 216ms
middleware /_next/static/css/app/layout.css
middleware /_next/static/chunks/webpack.js
middleware /_next/static/chunks/main-app.js
middleware /_next/static/chunks/app-pages-internals.js

When extending auth, extending auth I never receive correct information because the middleware does not pass any value in req.auth.

import { authOptions} from '@/auth'
import NextAuth from 'next-auth'

const { auth } = NextAuth(authOptions)

export default auth((req) =>
{
  console.log('auth middleware', req.auth)
})
[auth][error] JWTSessionError: Read more at https://errors.authjs.dev#jwtsessionerror
[auth][cause]: JWEInvalid: Invalid Compact JWE
    at compactDecrypt (webpack-internal:///(middleware)/./node_modules/.pnpm/jose@5.9.4/node_modules/jose/dist/browser/jwe/compact/decrypt.js:20:15)
    at jwtDecrypt (webpack-internal:///(middleware)/./node_modules/.pnpm/jose@5.9.4/node_modules/jose/dist/browser/jwt/decrypt.js:12:100)
    at Object.decode (webpack-internal:///(middleware)/./node_modules/.pnpm/@auth+core@0.37.2/node_modules/@auth/core/jwt.js:81:79)
    at Module.session (webpack-internal:///(middleware)/./node_modules/.pnpm/@auth+core@0.37.2/node_modules/@auth/core/lib/actions/session.js:23:39)
    at AuthInternal (webpack-internal:///(middleware)/./node_modules/.pnpm/@auth+core@0.37.2/node_modules/@auth/core/lib/index.js:51:77)
    at async Auth (webpack-internal:///(middleware)/./node_modules/.pnpm/@auth+core@0.37.2/node_modules/@auth/core/index.js:130:34)
    at async handleAuth (webpack-internal:///(middleware)/./node_modules/.pnpm/next-auth@5.0.0-beta.25_next@14.2.15_react-dom@18.3.1_react@18.3.1__react@18.3.1__react@18.3.1/node_modules/next-auth/lib/index.js:137:29)
    at async adapter (webpack-internal:///(middleware)/./node_modules/.pnpm/next@14.2.15_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/esm/server/web/adapter.js:178:16)
    at async /home/jdi/Desktop/@aldytaken/meca-store/node_modules/.pnpm/next@14.2.15_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/web/sandbox/sandbox.js:110:22
    at async runWithTaggedErrors (/home/jdi/Desktop/@aldytaken/meca-store/node_modules/.pnpm/next@14.2.15_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/web/sandbox/sandbox.js:107:9)
[auth][details]: {}
auth middleware null
prisma:client Prisma Client call: +193ms
prisma:client prisma.session.findUnique({
  where: {
    sessionToken: "4410481e-d59e-4053-9b27-193769d3e042"
  },
  include: {
    user: true
  }
}) +1ms
prisma:client Generated request: +0ms
prisma:client {
  "modelName": "Session",
  "action": "findUnique",
  "query": {
    "arguments": {
      "where": {
        "sessionToken": "4410481e-d59e-4053-9b27-193769d3e042"
      }
    },
    "selection": {
      "$composites": true,
      "$scalars": true,
      "user": {
        "arguments": {},
        "selection": {
          "$composites": true,
          "$scalars": true
        }
      }
    }
  }
}
 +1ms
prisma:client:libraryEngine sending request, this.libraryStarted: true +0ms
 GET / 200 in 208ms
auth middleware null
auth middleware null
auth middleware null
auth middleware null
auth middleware null
 GET / 200 in 40ms
auth middleware null
auth middleware null
auth middleware null
auth middleware null

When I try to use the middlewares from auth.ts:

export { auth as middleware } from '@/auth'
[auth][details]: {}
[auth][error] AdapterError: Read more at https://errors.authjs.dev#adaptererror
[auth][cause]: Error: PrismaClient is not configured to run in Edge Runtime (Vercel Edge Functions, Vercel Edge Middleware, Next.js (Pages Router) Edge API Routes, Next.js (App Router) Edge Route Handlers or Next.js Middleware). In order to run Prisma Client on edge runtime, either:
- Use Prisma Accelerate: https://pris.ly/d/accelerate
- Use Driver Adapters: https://pris.ly/d/driver-adapters

auth.ts

import NextAuth, { NextAuthConfig } from 'next-auth'
import { PrismaAdapter } from '@auth/prisma-adapter'
import Google from 'next-auth/providers/google'
import { Provider } from 'next-auth/providers'
import { prisma } from '@/prisma'

const providers: Provider[] =
[
  Google
]

const callbacks: NextAuthConfig['callbacks'] =
{
  async signIn({ profile }): Promise<boolean>
  {
    if (profile?.email?.endsWith('@gmail.com'))
      return true

    return false
  },
}

export const authOptions: NextAuthConfig =
{
  providers: providers,
  callbacks: callbacks
}

const _authOptions: NextAuthConfig =
{
  adapter: PrismaAdapter(prisma),
  ...authOptions
}

export const { handlers, signIn, signOut, auth } = NextAuth(_authOptions)

How to reproduce

Have the middleware active and load a page.

Expected behavior

No response

Prisma information

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

generator client {
  provider = "prisma-client-js"
}

model User {
  id            String          @id @default(auto()) @map("_id") @db.ObjectId
  name          String?
  email         String?         @unique
  emailVerified DateTime?
  image         String?
  role          String @default("user")
  accounts      Account[]
  sessions      Session[]

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

model Account {
  id                String  @id @default(auto()) @map("_id") @db.ObjectId
  userId            String  @db.ObjectId
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.String
  access_token      String? @db.String
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.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(auto()) @map("_id") @db.ObjectId
  sessionToken String   @unique
  userId       String   @db.ObjectId
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)

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

model VerificationToken {
  id         String   @id @default(auto()) @map("_id") @db.ObjectId
  identifier String
  token      String
  expires    DateTime

  @@unique([identifier, token])
}
import { PrismaClient } from '@prisma/client'

const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }

export const prisma = globalForPrisma.prisma || new PrismaClient()

if (process.env.NODE_ENV === 'development')
  globalForPrisma.prisma = prisma

Environment & setup

Prisma Version

prisma                  : 5.21.1
@prisma/client          : 5.21.1
Computed binaryTarget   : debian-openssl-3.0.x
Operating System        : linux
Architecture            : x64
Node.js                 : v22.9.0
Query Engine (Node-API) : libquery-engine bf0e5e8a04cada8225617067eaa03d041e2bba36 (at node_modules/.pnpm/@prisma+engines@5.21.1/node_modules/@prisma/engines/libquery_engine-debian-openssl-3.0.x.so.node)
Schema Engine           : schema-engine-cli bf0e5e8a04cada8225617067eaa03d041e2bba36 (at node_modules/.pnpm/@prisma+engines@5.21.1/node_modules/@prisma/engines/schema-engine-debian-openssl-3.0.x)
Schema Wasm             : @prisma/prisma-schema-wasm 5.21.1-1.bf0e5e8a04cada8225617067eaa03d041e2bba36
Default Engines Hash    : bf0e5e8a04cada8225617067eaa03d041e2bba36
Studio                  : 0.503.0
jkomyno commented 1 week ago

Hi @jdic, this is expected, as Edge Runtimes are only supported via the driverAdapters preview feature (driven by https://github.com/prisma/prisma/issues/21394), which allows you to plug in JS database drivers rather than the Rust drivers embedded in Prisma's Query Engine.

The databases providers currently supported are sqlite, postgresql, and mysql (PlanetScale / Vitess). I see you're using mongodb, for which we have no current plans.

Would you consider closing this issue in favor of a new one titled e.g. "Request: support mongodb driverAdapters"? Thanks!