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

Try signing with a different account. - Callback error #3830

Closed
2 of 5 tasks
0xChez opened this issue Jan 14, 2021 · 54 comments
Closed
2 of 5 tasks

Try signing with a different account. - Callback error #3830

0xChez opened this issue Jan 14, 2021 · 54 comments
Labels
adapters Changes related to the core code concerning database adapters bug Something isn't working help needed The maintainer needs help due to time constraint/missing knowledge prisma @auth/prisma-adapter

Comments

@0xChez
Copy link

0xChez commented Jan 14, 2021

Describe the bug
When trying to sign in to GitHub it says "Try signing with a different account."

Steps to reproduce

  • Clone orangopus/libby
  • click "Login"
  • Click "Sign in with GitHub"

Make sure to include the client ID and secret in .env as GITHUB_ID and GITHUB_SECRET

Expected behavior
I expected it to login and return to the app.

Screenshots or error logs
The error is
browser_7MIk0bI7BK

Feedback
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

  • Found the documentation helpful
  • Found documentation but was incomplete
  • Could not find relevant documentation
  • Found the example project helpful
  • Did not find the example project helpful
@balazsorban44
Copy link
Member

Please provide more context, (preferably a full reproduction repository with a link) otherwise we cannot help you.

My bad! I can see you added information about a repository, it was just hard to catch not being a link. 😅 Sorry. I'll check it out

@balazsorban44
Copy link
Member

Could you maybe set debug: true in your NextAuth options, and see if anything useful comes up in your console then? Also, what's the url of the page you are seeing the "Sign in with a different account" warning on?

@0xChez
Copy link
Author

0xChez commented Jan 14, 2021

Could you maybe set debug: true in your NextAuth options, and see if anything useful comes up in your console then? Also, what's the url of the page you are seeing the "Sign in with a different account" warning on?

Found the issue! User was already created so it was throwing an error.

[next-auth][error][oauth_callback_handler_error] PrismaClientKnownRequestError2 [PrismaClientKnownRequestError]: 
Invalid `prisma.user.create()` invocation:


  Unique constraint failed on the fields: (`name`)
    at PrismaClientFetcher.request (E:\libby\libby-web\node_modules\@prisma\client\runtime\index.js:78130:15)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'P2002',
  clientVersion: '2.14.0',
  meta: { target: [ 'name' ] }
}

Fixed this but getting a new error now...

[next-auth][error][session_error] TypeError: Cannot read property 'name' of null
    at E:\libby\libby-web\node_modules\next-auth\dist\server\routes\session.js:99:26
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (E:\libby\libby-web\node_modules\next-auth\dist\server\routes\session.js:22:103)
    at _next (E:\libby\libby-web\node_modules\next-auth\dist\server\routes\session.js:24:194)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
https://next-auth.js.org/errors#session_error

when logging out and back in.

@0xChez
Copy link
Author

0xChez commented Jan 14, 2021

Still getting the session error. Any updates?

@ovo
Copy link

ovo commented Jan 16, 2021

Experiencing this as well. Ref: #1119

@ghost
Copy link

ghost commented Jan 18, 2021

I went to bed, woke up, booted up my app and I started getting this error. It was working last night so not sure what happened.

[next-auth][error][oauth_callback_handler_error] PrismaClientKnownRequestError2 [PrismaClientKnownRequestError]: 
Invalid `prisma.user.create()` invocation:

Unique constraint failed on the fields: (`name`)
    at PrismaClientFetcher.request (/Users/adam/Development/nextjs/hackernews/node_modules/@prisma/client/runtime/index.js:78130:15)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'P2002',
  clientVersion: '2.14.0',
  meta: { target: [ 'name' ] }
} 
https://next-auth.js.org/errors#oauth_callback_handler_error

@balazsorban44
Copy link
Member

@williamluke4 this seems to be Prisma related. Any ideas?

@typeofweb
Copy link

I'm experiencing the same problem now for no apparent reason.
I'm using the Prisma client :)

@williamluke4
Copy link

Could someone who is experiencing this issue please post your Prisma schema and indicate whether you are using the stock nextauthjs/next-auth prisma adapter or the adapter from nextauthjs/adapters

@kailoon
Copy link

kailoon commented Apr 13, 2021

I am facing the same problem. I am using the Prisma Adapter.

adapter: Adapters.Prisma.Adapter({ prisma })

Prisma Schema

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

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

model Account {
  id                 Int       @default(autoincrement()) @id
  compoundId         String    @unique @map(name: "compound_id")
  userId             Int       @map(name: "user_id")
  providerType       String    @map(name: "provider_type")
  providerId         String    @map(name: "provider_id")
  providerAccountId  String    @map(name: "provider_account_id")
  refreshToken       String?   @map(name: "refresh_token")
  accessToken        String?   @map(name: "access_token")
  accessTokenExpires DateTime? @map(name: "access_token_expires")
  createdAt          DateTime  @default(now()) @map(name: "created_at")
  updatedAt          DateTime  @default(now()) @map(name: "updated_at")

  @@index([providerAccountId], name: "providerAccountId")
  @@index([providerId], name: "providerId")
  @@index([userId], name: "userId")

  @@map(name: "accounts")
}

model Session {
  id           Int      @default(autoincrement()) @id
  userId       Int      @map(name: "user_id")
  expires      DateTime
  sessionToken String   @unique @map(name: "session_token")
  accessToken  String   @unique @map(name: "access_token")
  createdAt    DateTime @default(now()) @map(name: "created_at")
  updatedAt    DateTime @default(now()) @map(name: "updated_at")

  @@map(name: "sessions")
}

model User {
  id            Int       @default(autoincrement()) @id
  name          String?
  email         String?   @unique
  emailVerified DateTime? @map(name: "email_verified")
  image         String?
  createdAt     DateTime  @default(now()) @map(name: "created_at")
  updatedAt     DateTime  @default(now()) @map(name: "updated_at")

  @@map(name: "users")
}

model VerificationRequest {
  id         Int      @default(autoincrement()) @id
  identifier String
  token      String   @unique
  expires    DateTime
  createdAt  DateTime  @default(now()) @map(name: "created_at")
  updatedAt  DateTime  @default(now()) @map(name: "updated_at")

  @@map(name: "verification_requests")
}

@talentlessguy
Copy link

Guys, I found out a simple solution for those who struggle with email auth. Just add a callback for signin and assign a user name there. Prisma will consume that name and user will be registered.

const options = {
  callback: {
    signIn(user, account, profile) {
        user.name = slug(user.email.slice(0, user.email.indexOf('@'))) // or whatever else
  
        return true
      }
  }
}

@balazsorban44 balazsorban44 transferred this issue from nextauthjs/next-auth May 3, 2021
@ndom91 ndom91 added bug Something isn't working help needed The maintainer needs help due to time constraint/missing knowledge labels May 24, 2021
@ndom91
Copy link
Member

ndom91 commented Jun 7, 2021

@williamluke4 anything to do here from our side?

@bhatvikrant
Copy link
Contributor

I am also facing this issue, and I am using the prisma client with Github OAuth

@williamluke4
Copy link

Hey, @bhatvikrant Do you have a reproduction I can look at?

From the above ☝️ errors it seems that the adapter is trying to create a new user but there is a unique constraint violation on the field name. Meaning that a user with that name already exists.

@bhatvikrant
Copy link
Contributor

Hey @williamluke4, I have currently stripped out nextauthjs from my application, but I'll set it up again in a separate branch on a public repo for you to look at. Please allow me a few hours, I will update you here.

NOTE: I can confirm one thing that no user record was added in my postgres db (on heroku), however the user did get registered on the github OAuth service.

@williamluke4
Copy link

Thanks, @bhatvikrant, I'll check it out when you are ready :)

@bhatvikrant
Copy link
Contributor

This is the code for a reproducible example @williamluke4

NOTE: The github oAuth on vercel preview deployment won't work since I have not added the github and my database environment variables in the vercel environment, but you can add your own environment variables for testing. Please let me know if I should add them.

Steps I took to setup nextauthjs in this project:

  1. ran yarn add next-auth
  2. Followed the steps in this guide to install next-auth/prisma-adapter@canary
  3. added database: process.env.DATABASE_URL in [...nextauth].js file
  4. This is how my github OAuth application registration looks like

Screenshot 2021-06-14 at 8 25 44 PM

5. added GITHUB_ID, GITHUB_SECRET, DATABASE_URL environment variables in .env.local
  1. import { signOut, useSession } from 'next-auth/client' used in src/components/Navbar/index.tsx for checking session usage.
  2. import { signIn } from 'next-auth/client' used in src/components/Auth/OAuthProviders.tsx for signing in.
  3. After doing all this, I start the next server using yarn dev
  4. then, go to http://localhost:3000/login, then click on github, that redirects me to http://localhost:3000/api/auth/signin
  5. then I click on Sign in with Github, login with my github credentials and then I get this error:

Screenshot 2021-06-14 at 8 46 24 PM

  1. In the nextjs server console, I get the following error

Screenshot 2021-06-14 at 8 47 56 PM

Thankyou @williamluke4 for helping out :)

@williamluke4
Copy link

Thanks @bhatvikrant, I'll have a dig around tomorrow morning

@williamluke4
Copy link

So there are quite a few different issues stuffed into this issue.

@bhatvikrant Your issue is because the GitHub providerAccountId given to the adapter is a number and in the database expects a string.

I don't know if this is expected behaviour and whether it should be fixed in the adapter or in the provider (@ndom91 @balazsorban44 ).

I've opened a draft PR that will ensure that the providerAccountId is converted to a string.

@ndom91
Copy link
Member

ndom91 commented Jun 15, 2021

Hey william, thanks for this!

You probably saw it, but theres an issue/PR related to this in the core repo already as well: #2108 + https://github.com/nextauthjs/adapters/issues/130

Balazs initially said he wanted to hold off on this change until the next major release since it seems like a breaking change. Some users will have already coded around it expecting it to be a number instead of a string, etc.

How do you see it? Would this be a breaking change in your opinion?

EDIT: Someone posted a workaround in that thread:

I'll leave this note here for the benefit of other people who might run into the same issue.

Until this gets fixed, use this workaround:

import NextAuth, { User as NextAuthUser } from 'next-auth'
interface NextAuthUserWithStringId extends NextAuthUser {
id: string
}

Providers.GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
      profile(profile) {
        return {
          id: profile.id.toString(),
          name: profile.name || profile.login,
          email: profile.email,
          image: profile.avatar_url,
        } as NextAuthUserWithStringId
      },
    }),

@bhatvikrant
Copy link
Contributor

Awesome! Thankyou @williamluke4 and @ndom91! This works for me now!

But whenever I login using github as mentioned above, the email is stored as null in my database, how can I enable email to be stored as well as soon as someone logs in?

Screenshot 2021-06-15 at 8 20 19 PM

EDIT: I can see that the docs mention:
Email address is not returned if privacy settings are enabled.

@freerg
Copy link

freerg commented Jun 16, 2021

@ndom91 Since the prisma adapter (non-legacy version) is marked as experimental, why not use @williamluke4's PR as a temporary measure until the version of nextauth with the updated github provider is available?
At that point you could undo the changes, or keep them to allow backwards compatibility with older versions of nextauth with the incompatible github provider code?

@spaceclottey
Copy link

I fixed this by removing the database: process.env.DATABASE_URL, that is there by default in [...nextauth].js if you copiedd it from the tutorial.

@EugeneGohh
Copy link

I fixed this by removing the database: process.env.DATABASE_URL, that is there by default in [...nextauth].js if you copiedd it from the tutorial.

Same here.

@DANISHPANDITA
Copy link

removed database line. still getting error

@robinMcA
Copy link

Looks like the return from the git hub provider has an extra value that is not in the example prisma schema.
I added refresh_token_expires_in Int? to my accont model so it looks like

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?
  oauth_token_secret String?
  oauth_token        String?
  refresh_token_expires_in        Int?

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

  @@unique([provider, providerAccountId])
}

accont creation from git hub work for me after this

@trulymittal
Copy link

The problem seems to be with the model provided on the page for PRISMA adapter, the fix (or hack) if it was missed, is to added the a new field like:

model Account {
...
refresh_token_expires_in Int?
}

Do the migrations and make sure that in DB the user/account does not already exist and then try out.

And now, No error like before as name: 'LinkAccountError' - the first time you log in, but your NOT logged in since of error, the USER row is created but NOT the ACCOUNT row and therefore the second time you try, you get the error as OAuthAccountNotLinked since now the second time the user is already present and auto account linking is NOT provided by default in next-auth

[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
https://next-auth.js.org/errors#oauth_callback_handler_error 
Invalid `prisma.account.create()` invocation:

{
  data: {
    provider: 'github',
    type: 'oauth',
    providerAccountId: 'ACCOUNT ID',
    access_token: 'HIDDEN,
    expires_at: 1632613683,
    refresh_token: 'HIDDEN',
    refresh_token_expires_in: 15638400,
    ~~~~~~~~~~~~~~~~~~~~~~~~
    token_type: 'bearer',
    scope: '',
    userId: 'ckldkjbfsdkjlfdefbsdfb2'
  }
}

Part of my related dependencies:

  "dependencies": {
    "@next-auth/prisma-adapter": "^0.5.2-next.15",
    "@prisma/client": "^2.30.3",
    "next": "11.1.2",
    "next-auth": "4.0.0-beta.2",
},
"devDependencies": {
    "prisma": "^2.30.3"
  }

NOTE: Though this fixed the issue, but the behavior is somewhat weird, I used the same exact application, at one place I am getting this error and on second instance I am not. The only difference being that the first application used sqlit and second uses postgres but even on changing postgres back to sqlite on the second instance the error remains the same, so even if the problem is solved or hacked, I am not able to justify myself as to why on first instance with sqlite this is running without this new field (refresh_token_expires_in)

@Seth-McKilla
Copy link

Seth-McKilla commented May 25, 2022

Hey @trulymittal not sure if you've resolved this already but nonetheless I was running into this exact issue. After digging around closed issues I found this Account schema that is working well for me: #3465 (comment)

No weird issues yet! 🤞

@hollerith
Copy link

prisma related issue solved for me by just generating the client again

npx prisma generate

@fullupe
Copy link

fullupe commented Sep 9, 2022

just follow the error path and add ? in front of the value

for (const key in newUser) {
const value = newUser[key];
if (value?.toDate)
newUser[key] = value.toDate();
else
newUser[key] = value;
}

@VaquarShaikh
Copy link

Try adding

session: {
    // Set to jwt in order to CredentialsProvider works properly
    strategy: "jwt",
  },

To [...nextauth]

@imrankhanjoya
Copy link

Its not about adapter its about next-auth lib issue can some one help me
next-auth][debug][CREATE_STATE] { state: 'O1k6DX0Isddd9wvUdsdnCRksudNFYQyk0ZVO4c8lqqePc', maxAge: 900 }
[next-auth][debug][CREATE_PKCE_CHALLENGE_VERIFIER] {
code_challenge: 'oEzh0AjPSnp7wIsdsdsdCtYPHVmdU-NDd39J7o',
code_challenge_method: 'S256',
code_verifier: 'mYB_6sdsdf8sd0nbTKvoTxeoAacW0w-tuZ_ASfUvITPs8',
PKCE_MAX_AGE: 900
}
[next-auth][debug][GET_AUTHORIZATION_URL] {
url: 'https://twitter.com/i/oauth2/authorize?client_id=UlVva1VQM0sxblRnWMVc6MTpjaQ&scope=users.read%20tweet.read%20offline.access&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fauth%2Fcallback%2Ftwitter&state=O1k6DXZNNgI0I9wvUnCRksudNFYQyk0ZVO4c8lqqePc&code_challenge=oEzh0AjPSnp7wICmdPiqEjCcZ7ZBU-NDd39J7o&code_challenge_method=S256',
cookies: [
{
name: 'next-auth.state',
value: 'eyJhbGciOiJkaXIiLCJlbmJBMjU2R0NNIn0..PkaCKXnqbDyGy-lr.FpYZLVHv9caJ3ITP4kQqW0uiyKyR-BYUzWUsd-d0F4XNk9uU-xts6VAUvD697y7oltF4pgcEEhMUvnTPbwryvDTWLqX4M-w73Td_n-jisl1Zgn7EWKi9C3JjrsHcvSXoxC-de-MUCGhR4XgRtXbnkR6WxQ.rDgOw9i9YQMYIdENxYg-6g',
options: [Object]
},
{
name: 'next-auth.pkce.code_verifier',
value: 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0sdQ8YT1x1hQUvSBE.02S7_YBK1ok4cRA0aa8MhcvRJ2ypHaznbVasAnhmvigiy1Jz-XNrKo0oYnR-qx5QRVWfKSmRxYI5l0-hoxp6T2Gpdpp273ATBgzQTJs7GYs5Enxjptkva4Vgr-Rw_aRal7W5G0pNHFfRYknc4FPH5cdMCEFoQFjJKSGdcwtks8lwdRSxanBJy6tw2rwxwQ.PJBK-sweSQg_K2RJMUMjA',
options: [Object]
}
],
provider: {
id: 'twitter',
name: 'Twitter',
version: '2.0',
type: 'oauth',
authorization: { url: 'https://twitter.com/i/oauth2/authorize', params: [Object] },
token: {
url: 'https://api.twitter.com/2/oauth2/token',
request: [AsyncFunction: request]
},
userinfo: { url: 'https://api.twitter.com/2/users/me', params: [Object] },
profile: [Function: profile],
checks: [ 'pkce', 'state' ],
idToken: false,
clientId: 'UlVva1VQM0sxblRnWnc2sdfadhhHH',
clientSecret: 'ffyz6bdNKWasdf1jOOevA4UQLr_IFmo',
signinUrl: 'http://localhost:3000/api/auth/signin/twitter',
callbackUrl: 'http://localhost:3000/api/auth/callback/twitter'
}
}
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error expected 200 OK, got: 403 Forbidden {
error: OPError: expected 200 OK, got: 403 Forbidden

@Ayushpandey80
Copy link

How to allow user to Connect Twitter / LinkedIn account (get access token permanently) after user is logged-in to the next-js app using next-auth's Google provider?

Exact Question

@jackypan1989
Copy link

I encountered this too. It means "There is something broken by unique things."
for example:

  1. forgot to add primary keys like @@unique([provider, providerAccountId])
  2. set email is unique, but somehow user login without email (like Twitter you can log in by phone number)

You need to add the key right or make temp emails.

@keshri95
Copy link

keshri95 commented Mar 4, 2023

I'm having same issue its a Promise even I placed context
uncaught (in promise) Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings. at it (blur.js:42:3933) at s.useContext (blur.js:42:5675) at cr (blur.js:57:31858) at blur.js:61:494 at blur.js:126:5191 at Generator.next (<anonymous>) at I (blur.js:126:4967)

@keshri95
Copy link

keshri95 commented Mar 4, 2023

Guys,
If you are encountered failed issue then your have to place secrete key
`providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
// ...add more providers here
],

secret: process.env.JWT_SECRET`

Get the secret key in from your terminal
openssl rand -base64 32

@thinkdj
Copy link

thinkdj commented Mar 5, 2023

@trulymittal Thanks for the direction. I was able to fix my issue.
NextAuth has mentioned these as small footnotes at https://next-auth.js.org/adapters/models#account

@ThangHuuVu
Copy link
Member

To everyone who is running into this issue, next-auth will forward every property it received from the provider to the DB, so for now you need to make sure that your DB schema matches the payload. Seems like this is still missing from docs, feel free to open a PR to improve it 🙏
Going forward, as @ndom91 mentioned in #3830 (comment), we want to flip this behavior to only accept a number of props and let developers specify what props they want to pass to DB.

@e-simpson
Copy link

e-simpson commented Mar 29, 2023

Issues with next-auth and GitHub provider when using Prisma and CockroachDB and the schema.prisma found in the documentation. Received sign in errors, had to update schema to use mappings.

@MrEmanuel
Copy link

For me it was a problem with the connection to the database.
Fix the environment variable, redeploy to vercel. Presto!

@mostafa1elgzaeere
Copy link

im faced this issue before , make sure you put ".env.local" file at the project folder , not in page folder or api folder or others

put it at the global folder

@Nateight8
Copy link

Awesome! Thankyou @williamluke4 and @ndom91! This works for me now!

But whenever I login using github as mentioned above, the email is stored as null in my database, how can I enable email to be stored as well as soon as someone logs in?

Screenshot 2021-06-15 at 8 20 19 PM

EDIT: I can see that the docs mention: Email address is not returned if privacy settings are enabled.

During my project work, I encountered an issue where the session was not being returned. However, when I downgraded the version of next-auth to ^4.10.3, the problem was resolved. It seems that the issue was related to the version of next-auth. Please note that this information might not be relevant to your current situation.

@MilanObrenovic
Copy link

I'm getting this error, but i'm connected to a hotspot of my android phone because the wifi in my house died. I think this causes a whole new set of problems

Anyone knows how to fix this problem when im connected to a mobile 4g hotspot network instead of wifi?

@natkucera
Copy link

Late to the game but the solution for me was a lot simpler than I could have imagined. I just restarted the server and everything works great now. Feel silly for not trying it sooner

@rshirani
Copy link

rshirani commented Aug 8, 2023

I am hitting this issue using google authentication with prisma. It was working fine before starting to integrate with Prisma.

@Wissaladd
Copy link

@rshirani i am having the same issue with the google provider did you manage to fix it

@umerpall
Copy link

umerpall commented Dec 1, 2023

I had a wrong "GOOGLE_CLIENT_SECRET" which was causing the problem.

@p-runge
Copy link

p-runge commented Dec 11, 2023

I encountered this too. It means "There is something broken by unique things." for example:

1. forgot to add primary keys like `@@unique([provider, providerAccountId])`

2. set email is unique, but somehow user login without email (like Twitter you can log in by phone number)

You need to add the key right or make temp emails.

I also noticed this error occurring when I tried to remove the email field from my User model. My goal was to only ask for Discord's identify scope to keep the amount of requested data as slim as possible.

I thought having the PK id in my User model would be enough since it's of course unique as well, but I guess it doesn't.
Not sure how to prevent that error here though.

@Akshay8122
Copy link

Akshay8122 commented Dec 18, 2023

Screenshot from 2023-12-18 12-09-13
error name: 'OAuthCallbackError',
code: undefined
I've missed giving a timeout in provider
 httpOptions: {
        timeout: 5000,
},
in provider and simply my error resolved
I hope this will work for you in case -- this kind of message in terminal: 'outgoing request timed out after 3500 ms'
      

@brandonhdez7
Copy link

i added this and it seemed to work for me, i'm only using the google provider
Screenshot 2024-01-25 at 10 08 14 PM

@diasmashikov
Copy link

If anyone is facing problems with getting the MongoDBAdapter, then listen to this:

My problem was that my MongoDBAdapter required the client connection to let it operate with the DB, however, I provided it with the Mongoose connection that would not let me work with it. So, if you are facing this situation, just create a separate file for the MongoClient connection and insert instead.

Here is the code for the MongoDB client connection

`import { MongoClient } from "mongodb";

if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
}

const uri = process.env.MONGODB_URI;
const options = {};

let client;
let mongoClientConnection: Promise;

if (process.env.NODE_ENV === "development") {
let globalWithMongo = global as typeof globalThis & {
_mongoClientPromise?: Promise;
};

if (!globalWithMongo._mongoClientPromise) {
if (!globalWithMongo._mongoClientPromise) {
client = new MongoClient(uri, options);
globalWithMongo._mongoClientPromise = client.connect();
}
}
mongoClientConnection = globalWithMongo._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
mongoClientConnection = client.connect();
}

export default mongoClientConnection;
`

@lenvaz
Copy link

lenvaz commented May 8, 2024

To resolve the issue, one of the ways is to make sure that you have the latest prisma models from here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
adapters Changes related to the core code concerning database adapters bug Something isn't working help needed The maintainer needs help due to time constraint/missing knowledge prisma @auth/prisma-adapter
Projects
None yet
Development

No branches or pull requests