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.66k stars 1.55k forks source link

`Error: PrismaClient is unable to be run under the Vercel Edge Runtime.` #20560

Open aayushxr opened 1 year ago

aayushxr commented 1 year ago

Bug description

In next13, If i change any route handlers to run on the edge while prisma is being called from that route handler, i get this error when deploying to vercel:

[17:31:38.494] /vercel/path0/.next/server/app/api/code/route.js:93
[17:31:38.495] In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues`)},o.DbNull=i.instances.DbNull,o.JsonNull=i.instances.JsonNull,o.AnyNull=i.instances.AnyNull,o.NullTypes={DbNull:i.classes.DbNull,JsonNull:i.classes.JsonNull,AnyNull:i.classes.AnyNull},t.Prisma.TransactionIsolationLevel=s({ReadUncommitted:"ReadUncommitted",ReadCommitted:"ReadCommitted",RepeatableRead:"RepeatableRead",Serializable:"Serializable"}),t.Prisma.UserApiLimitScalarFieldEnum={id:"id",userId:"userId",count:"count",createdAt:"createdAt",updatedAt:"updatedAt"},t.Prisma.UserSubscriptionScalarFieldEnum={id:"id",userId:"userId",stripeCustomerId:"stripeCustomerId",stripeSubscriptionId:"stripeSubscriptionId",stripePriceId:"stripePriceId",stripeCurrentPeriodEnd:"stripeCurrentPeriodEnd"},t.Prisma.SortOrder={asc:"asc",desc:"desc"},t.Prisma.QueryMode={default:"default",insensitive:"insensitive"},t.Prisma.NullsOrder={first:"first",last:"last"},t.Prisma.ModelName={UserApiLimit:"UserApiLimit",UserSubscription:"UserSubscription"},t.PrismaClient=class{constructor(){throw Error(`PrismaClient is unable to be run ${l}.
[17:31:38.496]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
[17:31:38.496] 
[17:31:38.496] Error: PrismaClient is unable to be run under the Vercel Edge Runtime.
[17:31:38.497] In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues
[17:31:38.497]     at new t.PrismaClient (/vercel/path0/.next/server/app/api/code/route.js:93:1080)
[17:31:38.497]     at 7916 (/vercel/path0/.next/server/app/api/code/route.js:81:948)
[17:31:38.507]     at __webpack_require__ (/vercel/path0/.next/server/edge-runtime-webpack.js:25:42)
[17:31:38.507]     at /vercel/path0/.next/server/app/api/code/route.js:112:96504
[17:31:38.508]     at webpackJsonpCallback (/vercel/path0/.next/server/edge-runtime-webpack.js:158:39)
[17:31:38.508]     at /vercel/path0/.next/server/app/api/code/route.js:1:51
[17:31:38.508]     at Script.runInContext (node:vm:141:12)
[17:31:38.508]     at runInContext (node:vm:291:6)
[17:31:38.508]     at evaluateInContext (/vercel/path0/node_modules/next/dist/server/web/sandbox/context.js:357:38)
[17:31:38.509]     at getRuntimeContext (/vercel/path0/node_modules/next/dist/server/web/sandbox/sandbox.js:69:9)
[17:31:38.509] 
[17:31:38.509] > Build error occurred
[17:31:38.509] Error: Failed to collect page data for /api/code
[17:31:38.510]     at /vercel/path0/node_modules/next/dist/build/utils.js:1156:15
[17:31:38.510]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
[17:31:38.510]   type: 'Error'
[17:31:38.510] }
[17:31:38.556] Error: Command "prisma generate && next build" exited with 1

here is a function i created to check api limit:

    const { userId } = auth();

    if (!userId) {
        return false;
    }

    const userApiLimit = await prismadb.userApiLimit.findUnique({
        where: {
            userId
        }
    });

    if (!userApiLimit || userApiLimit.count < FREE_CREDITS) {
        return true;
    } else {
        return false;
    }
}

when this is called in the route handler as

    const freetrial = await checkApiLimit()

vercel gives the error

How to reproduce

  1. create a next13 app
  2. create a function in lib/utils.ts where you call prisma
  3. call it in a route handler that has its runtime in the edge
  4. deploy the next13 app to vercel

Expected behavior

No response

Prisma information

Prisma Schema:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

datasource db {
  provider = "postgresql"
  url = env("DATABASE_PRISMA_URL") // uses connection pooling
  directUrl = env("DATABASE_URL_NON_POOLING") // uses a direct connection
}

model UserApiLimit {
  id        String   @id @default(uuid())
  userId    String   @unique
  count     Int      @default(0)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model UserSubscription {
  id        String   @id @default(uuid())
  userId     String   @unique
  stripeCustomerId String? @unique @map(name: "stripe_customer_id")
  stripeSubscriptionId String? @unique @map(name: "stripe_subscription_id")
  stripePriceId String? @unique @map(name: "stripe_price_id")
  stripeCurrentPeriodEnd DateTime? @map(name: "stripe_current_period_end")
}```

lib/prisma.ts

```import { PrismaClient } from "@prisma/client"

declare global {
  var prisma: PrismaClient | undefined
}

const prismadb = globalThis.prisma || new PrismaClient()
if (process.env.NODE_ENV !== "production") globalThis.prisma = prismadb

export default prismadb;

lib/utils.ts

export async function checkApiLimit() {
    const { userId } = auth();

    if (!userId) {
        return false;
    }

    const userApiLimit = await prismadb.userApiLimit.findUnique({
        where: {
            userId
        }
    });

    if (!userApiLimit || userApiLimit.count < FREE_CREDITS) {
        return true;
    } else {
        return false;
    }
}

/app/api/code/route.ts


const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

export const runtime = 'edge'; 

const openai = new OpenAIApi(configuration);

const instructionMessage: ChatCompletionRequestMessage = {
  role: "system",
  content: "...."
};

export async function POST(
  req: Request
) {
  try {
    const { userId } = auth();
    const body = await req.json();
    const { messages } = body;
    const freetrial = await checkApiLimit()
    const isPro = await checkSubscription();

    if (!userId) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    if (!configuration.apiKey) {
      return new NextResponse("OpenAI API Key not configured.", { status: 500 });
    }

    if (!messages) {
      return new NextResponse("Messages are required", { status: 400 });
    }

    if (!freetrial && !isPro) {
      return new NextResponse("You have reached your free trial limit. Please upgrade your account.", { status: 403 });
    }

    const response = await openai.createChatCompletion({
      model: "gpt-3.5-turbo",
      messages: [instructionMessage, ...messages]
    });
    await increaseApiLimit();
    return NextResponse.json(response.data.choices[0].message);
  } catch (error) {
    console.log('[CODE_ERROR]', error);
    return new NextResponse("Internal Error", { status: 500 });
  }
};

Environment & setup

Prisma Version

prisma                  : 5.1.1
@prisma/client          : 5.1.1
Current platform        : windows
Query Engine (Node-API) : libquery-engine 6a3747c37ff169c90047725a05a6ef02e32ac97e (at node_modules\@prisma\engines\query_engine-windows.dll.node)
Schema Engine           : schema-engine-cli 6a3747c37ff169c90047725a05a6ef02e32ac97e (at node_modules\@prisma\engines\schema-engine-windows.exe)
Schema Wasm             : @prisma/prisma-schema-wasm 5.1.1-1.6a3747c37ff169c90047725a05a6ef02e32ac97e
Default Engines Hash    : 6a3747c37ff169c90047725a05a6ef02e32ac97e
Studio                  : 0.492.0
janpio commented 1 year ago

Can you maybe help us with setting up a minimal reproduction and putting it on GitHub? We would love to try this ourselves. Thanks!

(Aside: The shadowDatabaseUrl is not needed with Vercel Postgre any more, you can remove that from your schema file)

aayushxr commented 1 year ago

Hi, Sorry for the late response, here is a github link to a next13 app where i highlighted it: https://github.com/aayush-rajagopalan/next13-prisma-edge.

here is the error given in vercel during deployment:

[08:47:09.915] /vercel/path0/.next/server/app/api/data/route.js:25
[08:47:09.916] In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues`)},o.DbNull=i.instances.DbNull,o.JsonNull=i.instances.JsonNull,o.AnyNull=i.instances.AnyNull,o.NullTypes={DbNull:i.classes.DbNull,JsonNull:i.classes.JsonNull,AnyNull:i.classes.AnyNull},t.Prisma.TransactionIsolationLevel=s({ReadUncommitted:"ReadUncommitted",ReadCommitted:"ReadCommitted",RepeatableRead:"RepeatableRead",Serializable:"Serializable"}),t.Prisma.UserScalarFieldEnum={id:"id",email:"email",name:"name",password:"password",createdAt:"createdAt",updatedAt:"updatedAt"},t.Prisma.SortOrder={asc:"asc",desc:"desc"},t.Prisma.QueryMode={default:"default",insensitive:"insensitive"},t.Prisma.NullsOrder={first:"first",last:"last"},t.Prisma.ModelName={User:"User"},t.PrismaClient=class{constructor(){throw Error(`PrismaClient is unable to be run ${l}.
[08:47:09.917]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     ^
[08:47:09.917] 
[08:47:09.919] Error: PrismaClient is unable to be run under the Vercel Edge Runtime.
[08:47:09.919] In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues
[08:47:09.919]     at new t.PrismaClient (/vercel/path0/.next/server/app/api/data/route.js:25:811)
[08:47:09.919]     at 3 (/vercel/path0/.next/server/app/api/data/route.js:13:48830)
[08:47:09.919]     at __webpack_require__ (/vercel/path0/.next/server/edge-runtime-webpack.js:25:42)
[08:47:09.920]     at /vercel/path0/.next/server/app/api/data/route.js:31:55485
[08:47:09.920]     at webpackJsonpCallback (/vercel/path0/.next/server/edge-runtime-webpack.js:158:39)
[08:47:09.920]     at /vercel/path0/.next/server/app/api/data/route.js:1:51
[08:47:09.920]     at Script.runInContext (node:vm:141:12)
[08:47:09.920]     at runInContext (node:vm:291:6)
[08:47:09.920]     at evaluateInContext (/vercel/path0/node_modules/next/dist/server/web/sandbox/context.js:357:38)
[08:47:09.920]     at getRuntimeContext (/vercel/path0/node_modules/next/dist/server/web/sandbox/sandbox.js:69:9)
[08:47:09.920] 
[08:47:09.920] > Build error occurred
[08:47:09.920] Error: Failed to collect page data for /api/data
[08:47:09.920]     at /vercel/path0/node_modules/next/dist/build/utils.js:1156:15
[08:47:09.920]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
[08:47:09.921]   type: 'Error'
[08:47:09.921] }
[08:47:09.958] Error: Command "npm run build" exited with 1

(Thank you for mentioning about the shadowDatabaseUrl, I'll change it on my project :) )

janpio commented 1 year ago

As expected, I can indeed reproduce this with your codebase - thanks for creating it!

gitpod /workspace/next13-prisma-edge (main) $ npm run build

> net13-prisma-edge@0.1.0 build
> next build

- info Creating an optimized production build  
- info Compiled successfully
- info Linting and checking validity of types  
- info Collecting page data ../workspace/next13-prisma-edge/.next/server/app/api/data/route.js:25
In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues`)},o.DbNull=i.instances.DbNull,o.JsonNull=i.instances.JsonNull,o.AnyNull=i.instances.AnyNull,o.NullTypes={DbNull:i.classes.DbNull,JsonNull:i.classes.JsonNull,AnyNull:i.classes.AnyNull},t.Prisma.TransactionIsolationLevel=s({ReadUncommitted:"ReadUncommitted",ReadCommitted:"ReadCommitted",RepeatableRead:"RepeatableRead",Serializable:"Serializable"}),t.Prisma.UserScalarFieldEnum={id:"id",email:"email",name:"name",password:"password",createdAt:"createdAt",updatedAt:"updatedAt"},t.Prisma.SortOrder={asc:"asc",desc:"desc"},t.Prisma.QueryMode={default:"default",insensitive:"insensitive"},t.Prisma.NullsOrder={first:"first",last:"last"},t.Prisma.ModelName={User:"User"},t.PrismaClient=class{constructor(){throw Error(`PrismaClient is unable to be run ${l}.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    ^

Error: PrismaClient is unable to be run under the Vercel Edge Runtime.
In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues
    at new t.PrismaClient (/workspace/next13-prisma-edge/.next/server/app/api/data/route.js:25:811)
    at 126 (/workspace/next13-prisma-edge/.next/server/app/api/data/route.js:13:48830)
    at __webpack_require__ (/workspace/next13-prisma-edge/.next/server/edge-runtime-webpack.js:25:42)
    at /workspace/next13-prisma-edge/.next/server/app/api/data/route.js:31:55485
    at webpackJsonpCallback (/workspace/next13-prisma-edge/.next/server/edge-runtime-webpack.js:158:39)
    at /workspace/next13-prisma-edge/.next/server/app/api/data/route.js:1:51
    at Script.runInContext (node:vm:141:12)
    at runInContext (node:vm:291:6)
    at evaluateInContext (/workspace/next13-prisma-edge/node_modules/next/dist/server/web/sandbox/context.js:357:38)
    at getRuntimeContext (/workspace/next13-prisma-edge/node_modules/next/dist/server/web/sandbox/sandbox.js:69:9)

> Build error occurred
Error: Failed to collect page data for /api/data
    at /workspace/next13-prisma-edge/node_modules/next/dist/build/utils.js:1156:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  type: 'Error'
}

Unfortunately, this is currently expected for Prisma Client: https://github.com/prisma/prisma/issues/20566 The Edge Runtime is a limited environment that does not allow direct communication to databases via TCP sockets and also imposes other limitations that are a problem for Prisma Client.

There are two "workarounds" right now:

  1. Use Prisma DataProxy to talk to your database and generate your Client with prisma generate --data-proxy, then import @prisma/client/edge into your app. This will generate an edge-optimized Prisma Client that talks to Dataproxy via HTTP. Minimal PR needed: https://github.com/Aayush-Rajagopalan/next13-prisma-edge/pull/1 (I know this is not a universal solution as this is a commercial product from Prisma)
  2. Do not use the edge runtime. export const runtime = "nodejs"; will configure your project to deploy its API functions as a serverless function, which Prisma already supports as it has the necessary functionality.

We are working on supporting the Vercel Edge Runtime, and Edge Functions in general, better in Prisma right now. Because of the platform limitations, that will always work slightly differently than using Prisma in a Node.js or serverless environment, but we will do our best to communicate that via documentation and - if needed - error messages. Please follow https://github.com/prisma/prisma/issues/20566 for updates.

aayushxr commented 1 year ago

As suggested, I tried using prisma dataproxy on my original project, changing @prisma/client to @prisma/client/edge and changing prisma generate to prisma generate --data-proxy. The build is succeeding now, however, I get this error in production

ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E42P05), message: "prepared statement \"s3\" already exists", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(412), routine: Some("StorePreparedStatement") }) }), transient: false })
janpio commented 1 year ago

Are you using Vercel Postgres? They have a connection string that adds pgbouncer=true, when you use that one this problem should not appear. You can also use the not pooled connection string in your app directly to also avoid this.

aayushxr commented 1 year ago

Yes, I am using Vercel Postgres, however, the URL I'm using is the prisma data proxy and that does not allow pgbouncer. What is the solution for this?

janpio commented 1 year ago

You configure the connection string that Prisma Data Proxy is using when you create the environment - and it should support PgBouncer just fine. Add the pgbouncer=true there, or use the non-pooled connection string when creating the environment.

scottmcpherson commented 1 year ago

I can confirm that the Prisma data proxy doesn't like pgbouncer in the URL. I tried using the value provided to me by vercel for the env var POSTGRES_PRISMA_URL.

I then tried to use the POSTGRES_URL env var for the data proxy, and that allowed me to create the connection string, but now I'm getting the same error as @Aayush-Rajagopalan ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E42P05), message: "prepared statement \"s0\" already exists", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(412), routine: Some("StorePreparedStatement") }) }), transient: false })

janpio commented 1 year ago

I can confirm that the Prisma data proxy doesn't like pgbouncer in the URL. I tried using the value provided to me by vercel for the env var POSTGRES_PRISMA_URL.

Indeed, sorry I was not aware:

image

I then tried to use the POSTGRES_URL env var for the data proxy, and that allowed me to create the connection string, but now I'm getting the same error

Here are example URLs from my Vercel Postgres:

POSTGRES_URL="postgres://default:...@ep-square-bar-649785-pooler.eu-central-1.postgres.vercel-storage.com:5432/verceldb"
POSTGRES_PRISMA_URL="postgres://default:...@ep-square-bar-649785-pooler.eu-central-1.postgres.vercel-storage.com:5432/verceldb?pgbouncer=true&connect_timeout=15"
POSTGRES_URL_NON_POOLING="postgres://default:...@ep-square-bar-649785.eu-central-1.postgres.vercel-storage.com:5432/verceldb"

You should be able to use POSTGRES_URL_NON_POOLING in Prisma Data Proxy successfully. Not that it is identical to POSTGRES_URL just without the -pooler after the "number" in the hostname.

aayushxr commented 1 year ago

I can confirm that the Prisma data proxy doesn't like pgbouncer in the URL. I tried using the value provided to me by vercel for the env var POSTGRES_PRISMA_URL.

I then tried to use the POSTGRES_URL env var for the data proxy, and that allowed me to create the connection string, but now I'm getting the same error as @Aayush-Rajagopalan ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Error { kind: Db, cause: Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState(E42P05), message: "prepared statement \"s0\" already exists", detail: None, hint: None, position: None, where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("prepare.c"), line: Some(412), routine: Some("StorePreparedStatement") }) }), transient: false })

Hi, I got around this issue by using the NON_POOLING url, it seems to be different than the PRISMA_URL

scottmcpherson commented 1 year ago

I would imagine there are performance implications when not using the pooling URL, or is connection pooling enabled by Prisma Data Proxy?

janpio commented 1 year ago

Yes, that is one of the core features of Prisma Data Proxy: https://www.prisma.io/data-platform/proxy That being said, this limitation in Data Proxy is pretty weird and I started an internal discussion to remove it so the pooled connection string can be used as well. No reason why our Proxy can not talk to a connection pooler like PgBouncer.

ntubrian commented 1 year ago

got the same issue here, originally I thought I made wrong syntax.

thanks to this thread and all replies, I known I'm not alone lol

janpio commented 1 year ago

Can you describe how your project is set up @ntubrian (or anyone else)? We will remove this limitation soon, and the more projects we have to try it out, the better our development will work. Thanks!

wellitonscheer commented 1 year ago

If like me you just need get something from the database, for now what i did was a fetch to my api.

const request = await fetch("http://localhost:3000/api/database/table", {
  method: "GET",
  headers: {
    "Content-Type": "application/json",
  },
});
const response =  await request.json()

Vercel Edge Runtime Functions

zjq000100 commented 1 year ago

https://www.prisma.io/docs/data-platform/accelerate/what-is-accelerate

Accelerate is a global database cache available in 300 locations that you can use to achieve up to 1000x faster database queries.

Its main features are:

  • a global cache
  • scalable connection pool for serverless and edge applications
  • usage of Prisma Client at the edge (e.g. in Cloudflare Workers or Vercel Edge Functions)

The goal of Accelerate is to improve response times and reduce database load. It works by caching data at the edge using established caching patterns that you control.

While Accelerate is beneficial for all types of applications, being at the edge provides additional benefits to edge function environments like Vercel Edge Functions, Cloudflare Workers, and Deno Deploy. Cache hits can be served from data centers near the user regardless of the region of the database.

cblberlin commented 12 months ago

my solution: go to https://www.prisma.io/data-platform/accelerate, create account, connect with your current projet, link the url string with your url(by copying the DATABASE_URL that you probably stored at .env), choose the location that near you. Then follow the instruction tha accelerate give you to modify your existing code, it should probably work

BTW: i'm following the same tutorial that antonio made on youtube, i don't know why he didn't have the same issue

dracoalv commented 10 months ago

This happens because probably

my solution: go to https://www.prisma.io/data-platform/accelerate, create account, connect with your current projet, link the url string with your url(by copying the DATABASE_URL that you probably stored at .env), choose the location that near you. Then follow the instruction tha accelerate give you to modify your existing code, it should probably work

BTW: i'm following the same tutorial that antonio made on youtube, i don't know why he didn't have the same issue

This happens because probably you are fetch user using an server action inside jwt callback when u should use the user provided by JWT callback parameter, same for account parameter.

The problem when using this method is that any changes to the user will not take effect in real time, the user will need to relog to reflect the changes.

Edit: misspelling.

satyaprakash-yadav commented 9 months ago

Screenshot (83)

satyaprakash-yadav commented 9 months ago

can anyone help me ?

suraj1294 commented 9 months ago

change import of import { PrismaClient } from "@prisma/client"; to import { PrismaClient } from "@prisma/client/edge";

worked for me!

satyaprakash-yadav commented 9 months ago

but i my case import { PrismaClient } from "@prisma/client/edge"; working but login authication not working because neon restrict to access login credentials so what i do ?

cblberlin commented 9 months ago

but i my case import { PrismaClient } from "@prisma/client/edge"; working but login authication not working because neon restrict to access login credentials so what i do ?

really no idea...maybe try some other postresql provider...i'm thinking of using supabase or convex on next project

janpio commented 8 months ago

Hey everyone!

We just released Prisma ORM version 5.11.0 which includes a preview feature for Edge Functions support for Vercel Edge Functions and Middleware (and Cloudflare Workers and Pages) in Prisma ORM 🥳

Please give it a try, and let us know how it goes! If you encounter any problems, please create a new bug report issue, or if the problem is driver adapter specific, use the feedback discussions for @prisma/adapter-neon, @prisma/adapter-planetscale, or @prisma/adapter-libsql / Turso 🙇

Zeven100 commented 7 months ago

thanks @janpio , I was getting frustrated with the same issue . But using prisma generate --data-proxy helped me resolve the issue .

jkomyno commented 5 months ago

Hi @Aayush-Rajagopalan, @Zeven100 and others, can you please retry with the following (unstable) version of prisma and @prisma/client? 5.15.0-integration-client-dynamic-wasm-imports.1.

We believe that such version contains the fix to this issue. We expect this to be released in the next stable Prisma version, 5.15.0, next week.

You will need to use the driverAdapters preview feature in your schema

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

and you'd need to import the Prisma Client via

import { PrismaClient } from '@prisma/client'

Thanks!

Zeven100 commented 5 months ago

Hi @Aayush-Rajagopalan, @Zeven100 and others, can you please retry with the following (unstable) version of prisma and @prisma/client? 5.15.0-integration-client-dynamic-wasm-imports.1.

We believe that such version contains the fix to this issue. We expect this to be released in the next stable Prisma version, 5.15.0, next week.

You will need to use the driverAdapters preview feature in your schema

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

and you'd need to import the Prisma Client via

import { PrismaClient } from '@prisma/client'

Thanks!

Thanks @jkomyno 😊

mdjahidhasan009 commented 5 months ago

Can I use Superbase with Postgres, and Next-Auth V5 for authentication inside the app route?

janpio commented 5 months ago

Please open a discussion @mdjahidhasan009 instead of asking in an issue reporting a bug. Thank you.

realtebo commented 2 months ago

actually i'm trying to use Next-auth 5 and postgres (supabase) and app route

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  pages: {
    signIn: "/auth/signIn",
  },
  adapter: PrismaAdapter(prisma),
  providers: [
    github
  ],
  callbacks: {
    async authorized({
      request,
      auth,
    }: {
      request: NextRequest;
      auth: null | Session;
    }) {
      console.log("in authorized function", request);

      // Se si ritorna un false, l'utente viene rediretto alla pagina di login
      // return false;

      // Se si ritorna un true, l'utente viene considerato loggato
      // return true;

      // L'ideale è verificare se c'è un utente in sessione
      return !!auth?.user;
    },
  },
});

Login is not working (signin also).

SessionTokenError: Read more at https://errors.authjs.dev#sessiontokenerror [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:

The user is created on db The account idem The session idem

but simply user results as not logged.

jelmd commented 1 month ago

Neither NextJS nor Auth0 nor Prisma documentation helps (and actually it seems, that most people do not understand this edge-runtime non-sense). Actually we run all our apps on our own servers using nodejs. So why do we get errors like PrismaClient failed to initialize because it wasn't configured to run in this environment ... it is running on nodejs and actually seems to throw the exception for no reason, because I see, that the db gets queried and proper results get returned. So it seems, that Prisma is buggy and doesn't really check, what is needed (and allows to be fooled by other nextjs non-sense).

So proper documentation of PrismaClientValidationError with "edge runtime context" would better help to understand the problem, and proper advice, how to workaround it is really needed especially for environments, which always use its own servers with nodejs (I would guess this is >90%) and proper examples for MySQL. All what I have found so far, does not work.