nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
25.01k stars 3.53k forks source link

Invalid `p.account.findUnique()` invocation with prisma #3815

Closed MattA-Official closed 2 years ago

MattA-Official commented 2 years ago

Title

Invalid p.account.findUnique() invocation with prisma

How to reproduce ☕️

next-auth: 4.0.0-beta.7 @next-auth/prisma-adapter: 0.5.2-next.19

/pages/api/[...nextauth].ts

import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { hasBetaAccess } from 'lib/backend-utils';
import { prisma } from 'lib/prisma';
import NextAuth from 'next-auth';
import Discord from 'next-auth/providers/discord';

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    Discord({
      clientId: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      authorization: 'https://discord.com/api/oauth2/authorize?scope=identify+guilds',
      profile(profile) {
        let image_url: string;

        if (profile.avatar === null) {
          const defaultAvatarNumber = parseInt(profile.discriminator, 10) % 5;
          image_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`;
        } else {
          const format = profile.avatar.startsWith('a_') ? 'gif' : 'png';
          image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`;
        }

        return {
          id: profile.id,
          username: profile.username,
          discriminator: profile.discriminator,
          avatar: image_url,
          profile: {
            vanity: profile.id,
            user_id: profile.id,
          },
        };
      },
    }),
  ],
  callbacks: {
    async session({ session, user }) {
      return {
        ...session,
        user,
      };
    },
    async signIn({ user }) {
      // Check for a development environment
      if (process.env.NODE_ENV === 'development') return true;

      // Check if the user has access to the beta
      const betaUser = user.beta || (await hasBetaAccess(user.id));
      return betaUser ? true : '/?error=AccessDenied';
    },
  },
});

Account schema

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

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

  @@unique([provider, providerAccountId])
  @@map("accounts")
}

Your question/bug report 📓

The bug below results from the above code. It is worth noting I am using MongoDB and not any sort of SQL.

Invalid `p.account.findUnique()` invocation in
C:\Users\folder\path\node_modules\@next-auth\prisma-adapter\dist\index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique({
           where: {
             provider_providerAccountId: {
             ~~~~~~~~~~~~~~~~~~~~~~~~~~
               providerAccountId: '366652352125599744',
               provider: 'discord'
             }
           },
           select: {
             user: true
           }
         })

Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUniqueInput. Available args:

type AccountWhereUniqueInput {
  id?: String
}

Contributing 🙌🏽

Yes, I am

MattA-Official commented 2 years ago

This is similar to nextauthjs/adapters#288 but there are a few differences that are big enough to give me a reason to create a new issue.

balazsorban44 commented 2 years ago

There is a separate MongoDB adapter. MongoDB with Prisma hasn't been tested.

balazsorban44 commented 2 years ago

Sorry, closed by accident. Would be happy to add support/tests, but currently, I cannot speak of how to get this working. Although the issue doesn't seem to be MongoDB specific.

Could you see if it works without the mapping stuff on the schema?

A full reproduction I can clone and test instead of code snippets would help a lot in resolving this as well!

MattA-Official commented 2 years ago

Currently testing over on https://github.com/TeamDmod/dmod/tree/prisma, the entire codebase is a mess so it's being rewritten. Just started work on integrating prisma as the ORM today.

I would be happy to help run some tests, and I will try to reproduce the issue in a clean project. I shall try without the mapping to snake_case tomorrow.

ndom91 commented 2 years ago

So based off of your debug output, it doesn't look like your Account model has any other available unique fields to query on, even though the [provider, providerAccountId] is clearly defined in the schema.. :thinking:

See:

Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUniqueInput. Available args:

type AccountWhereUniqueInput {
  id?: String
}

However, looking through the docs, I see that you can optionally give @unique and @@unique values a specific name now to query by (https://www.prisma.io/docs/concepts/components/prisma-schema/names-in-underlying-database#constraint-and-index-names)

i.e. @@unique([pageId, readerId], name: "bookmark_page_id_reader_id_key")

You may also be able to use findOne instead

mateonunez commented 2 years ago

Same issue here, I'm using Google Provider with Prisma Adapter.

error - unhandledRejection: Error: 
Invalid `p.account.findUnique()` invocation in
/Users/mateonunez/Documents/dev/boilerplates/base-fullstack-javascript/node_modules/@next-auth/prisma-adapter/dist/index.js:11:13

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
  The table `(not available)` does not exist in the current database.
MattA-Official commented 2 years ago

Same issue here, I'm using Google Provider with Prisma Adapter.

error - unhandledRejection: Error: 
Invalid `p.account.findUnique()` invocation in
/Users/mateonunez/Documents/dev/boilerplates/base-fullstack-javascript/node_modules/@next-auth/prisma-adapter/dist/index.js:11:13

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
  The table `(not available)` does not exist in the current database.

No, that looks like a different error. Have you made sure to run npx prisma migrate?

mateonunez commented 2 years ago

@MattA-Official yes, I've done.

I think is the same issue. I'm just mapping my models. But when the Google auth is finished, Prisma Provider got me that error.

MattA-Official commented 2 years ago

The error messages say two completely different things, it could be related, but I doubt it. The original one is where an individual field isn't unique for some reason. Your one is where the table itself doesn't exist in the database, which isn't a possible error with mongo as it doesn't check for these things.

mateonunez commented 2 years ago

@MattA-Official anyway this is what I got when I remove the @unique in Account model:

[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
https://next-auth.js.org/errors#oauth_callback_handler_error 
Invalid `p.account.findUnique()` invocation in
/Users/mateonunez/Documents/dev/boilerplates/base-fullstack-javascript/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique({
           where: {
             provider_providerAccountId: {
             ~~~~~~~~~~~~~~~~~~~~~~~~~~
               providerAccountId: '117367287917655988076',
               provider: 'google'
             }
           },
           select: {
             user: true
           }
         })

Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUniqueInput. Available args:

type AccountWhereUniqueInput {
  id?: String
}

It seems the same output!

These are my Models:

// 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"
  previewFeatures = ["dataProxy"]
}

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

model Account {
  id                String   @id @default(cuid())
  userId            String   @map("user_id")
  type              String
  provider          String
  providerAccountId String   @map("provider_account_id")
  refresh_token     String?
  access_token      String?
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String?
  session_state     String?
  createdAt         DateTime @default(now()) @map(name: "created_at")
  updatedAt         DateTime @default(now()) @map(name: "updated_at")

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

  @@map("accounts")
}

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

  accounts Account[]
  sessions Session[]

  @@map("users")
}

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

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

  @@map("sessions")
}

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

  @@map("verification_tokens")
}
sonipranjal commented 2 years ago

I have a similar issue when I added supabase DB connection string in environment variable.


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

Please make sure to provide valid database credentials for the database server at `db.xyz.supabase.co`.
    at cb (/Users/pranjalsoni/Desktop/projects/course project/code-course-platform/node_modules/@prisma/client/runtime/index.js:38697:17)
    at async getUserByAccount (/Users/pranjalsoni/Desktop/projects/course project/code-course-platform/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29) {
  name: 'GetUserByAccountError',
  code: undefined
ndom91 commented 2 years ago

@mateonunez you're model seems to be missing one crucial line from our default model, at the end of the Account section, please add:

@@unique([provider, providerAccountId])

We've manually told the prisma model that provider__providerAccountId should be unique, and yuo're model seems to be missing that, therefore the failed request there.

See: https://github.com/nextauthjs/adapters/blob/1923ebf1f69ee9c4549a9c80703d7d795da0827b/packages/prisma/prisma/schema.prisma#L36

EDIT: P.S. if you remember where you got yuor schema from, I'd love to update the docs if that was missing somewhere. I just double checked the Prisma adapters page, and this @@unique.. statement seems to be there in all instances though (https://next-auth.js.org/adapters/prisma) :thinking:

ndom91 commented 2 years ago

@MattA-Official the crux of your issue seems to be the same, right? That @@unique([provider, providerAccountId]) isn't being applied, so to speak.

I did some digging through the Prisma docs, and it seems in the case of MongoDB, you must create this @@unique compound index yourself - Prisma can't/doesn't (not sure) do it in Mongo yet.

See: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#mongodb-4

sonipranjal commented 2 years ago

Here is my models, I am not able to figure out what is going on 🥲


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

  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)
}

model User {
  id            String    @id @default(cuid())
  stripeId      String?   @unique
  isSubscribed  Boolean   @default(false)
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  courses       Course[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}
ndom91 commented 2 years ago

Soni, without any further information, it seems like prisma can't login to your supabase database. Are you sure the credentials are entered correctly? Does supabase require any sort of IP Whitelisting maybe?

sonipranjal commented 2 years ago

Hi @ndom91, thank you for your response.

krishnaUIDev commented 2 years ago

I am facing same issue, I did migrate npx prisma migrate.

model Account {
  id                 String    @id @default(cuid())
  userId             String
  providerType       String
  providerId         String
  providerAccountId  String?
  refreshToken       String?
  accessToken        String?
  accessTokenExpires DateTime?
  createdAt          DateTime  @default(now())
  updatedAt          DateTime  @updatedAt
  user               User      @relation(fields: [userId], references: [id])
  @@unique([providerId, providerAccountId])
}
ndom91 commented 2 years ago

@krishnaUIDev can you provide more detail as well? i.e. your config and copy of the error msg, etc. Thanks!

@sonipranjal okay but it still seems that prisma is having issues. Can you successfully run npx prisma studio to open the database viewer UI thing? Does that connect successfully? If so, can you share how yuo're using that p.account.findUnique() exactly?

ndom91 commented 2 years ago

nextauthjs/next-auth has been migrated to a monorepository. The adapters code can now be found there under packages/adapter-*. Thanks for your interest in the project!

ChrisB007 commented 2 years ago

Hello all, I was wondering if this issue has been resolved. I am experiencing a similar issue:

Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUniqueInput. Did you mean `providerId_providerAccountId`? Available args:
type AccountWhereUniqueInput {
  id?: String
  providerId_providerAccountId?: AccountProviderIdProviderAccountIdCompoundUniqueInput
}

 Error: 
Invalid `p.account.findUnique()` invocation in
/Users/blkboxng/Desktop/publicTradesProperties/Prod-tuberDome/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique({
           where: {
             provider_providerAccountId: {
             ~~~~~~~~~~~~~~~~~~~~~~~~~~
               providerAccountId: '108759031429510900958',
               provider: 'google'
             }
           },
           select: {
             user: true
           }
         })

Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUniqueInput. Did you mean `providerId_providerAccountId`? Available args:
type AccountWhereUniqueInput {
  id?: String
  providerId_providerAccountId?: AccountProviderIdProviderAccountIdCompoundUniqueInput
}

Please advice

ndom91 commented 2 years ago

Hello all, I was wondering if this issue has been resolved. I am experiencing a similar issue:

Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUniqueInput. Did you mean `providerId_providerAccountId`? Available args:
type AccountWhereUniqueInput {
  id?: String
  providerId_providerAccountId?: AccountProviderIdProviderAccountIdCompoundUniqueInput
}

 Error: 
Invalid `p.account.findUnique()` invocation in
/Users/blkboxng/Desktop/publicTradesProperties/Prod-tuberDome/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique({
           where: {
             provider_providerAccountId: {
             ~~~~~~~~~~~~~~~~~~~~~~~~~~
               providerAccountId: '108759031429510900958',
               provider: 'google'
             }
           },
           select: {
             user: true
           }
         })

Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUniqueInput. Did you mean `providerId_providerAccountId`? Available args:
type AccountWhereUniqueInput {
  id?: String
  providerId_providerAccountId?: AccountProviderIdProviderAccountIdCompoundUniqueInput
}

Please advice

It looks like you just have a small typo. provider_ providerAccountId should be providerId_providerAccountId.

johnstjoe commented 2 years ago

I had this problem and resolved it by directly naming the unique constraint in the Account model:

model Account {
  //...
  @@unique([provider, providerAccountId], name: "provider_providerAccountId")
}
stale[bot] commented 2 years ago

It looks like this issue did not receive any activity for 60 days. It will be closed in 7 days if no further activity occurs. If you think your issue is still relevant, commenting will keep it open. Thanks!

stale[bot] commented 2 years ago

To keep things tidy, we are closing this issue for now. If you think your issue is still relevant, leave a comment and we might reopen it. Thanks!

ImValerio commented 2 years ago

Similar issue with MySQL

message: "Cannot read property 'findUnique' of undefined",
  stack: "TypeError: Cannot read property 'findUnique' of undefined\n" +
    '    at getUserByAccount (.....\\node_modules\\@next-auth\\prisma-adapter\\dist\\index.js:12:45)

Essentially in the prisma adapter p.account is undefined for some reason.

This is the 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 = "mysql"
  url      = env("DATABASE_URL")
}

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

  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)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

And this is the [...nextauth].js config

import NextAuth from "next-auth/next";
import GithubProvider from "next-auth/providers/github"
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient()

export default NextAuth({
    adapter: PrismaAdapter({ prisma }),
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET
        })
    ],
    secret: process.env.SECRET
})

Any idea?

ndom91 commented 2 years ago

Similar issue with MySQL

message: "Cannot read property 'findUnique' of undefined",
  stack: "TypeError: Cannot read property 'findUnique' of undefined\n" +
    '    at getUserByAccount (.....\\node_modules\\@next-auth\\prisma-adapter\\dist\\index.js:12:45)

...

And this is the [...nextauth].js config

import NextAuth from "next-auth/next";
import GithubProvider from "next-auth/providers/github"
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient()

export default NextAuth({
    adapter: PrismaAdapter({ prisma }),
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET
        })
    ],
    secret: process.env.SECRET
})

Any idea?

Hey so one small thing I noticed, the prisma client instance should be passed to the adapter directly as the first argument, not in an object. i.e.

adapter: PrismaAdapter(prisma)
ImValerio commented 2 years ago

Similar issue with MySQL

message: "Cannot read property 'findUnique' of undefined",
  stack: "TypeError: Cannot read property 'findUnique' of undefined\n" +
    '    at getUserByAccount (.....\\node_modules\\@next-auth\\prisma-adapter\\dist\\index.js:12:45)

... And this is the [...nextauth].js config

import NextAuth from "next-auth/next";
import GithubProvider from "next-auth/providers/github"
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client"

const prisma = new PrismaClient()

export default NextAuth({
    adapter: PrismaAdapter({ prisma }),
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET
        })
    ],
    secret: process.env.SECRET
})

Any idea?

Hey so one small thing I noticed, the prisma client instance should be passed to the adapter directly as the first argument, not in an object. i.e.

adapter: PrismaAdapter(prisma)

I feel so dumb, you are right now all work fine!

birdmii commented 2 years ago

Similar issue here as well? I got this error below in Vercel realtime logs. My auth flow is working perfectly on local. But in the production. I faced this issue.

[GET] /api/auth/callback/github?code=8eedb3909bc5419b1095&state=yK9ZYFLBFfvrQxuucVa6w5xssbROWCt570Ay_wynvqw
17:42:55:53
2022-05-16T08:42:55.886Z    0212a91e-aa6a-4dd1-b62c-bddaba2f6a39    ERROR   [next-auth][error][adapter_error_getUserByAccount] 
https://next-auth.js.org/errors#adapter_error_getuserbyaccount Cannot read property 'findUnique' of undefined {
  message: "Cannot read property 'findUnique' of undefined",
  stack: "TypeError: Cannot read property 'findUnique' of undefined\n" +
    '    at getUserByAccount (/var/task/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45)\n' +
    '    at _callee2$ (/var/task/node_modules/next-auth/core/errors.js:315:29)\n' +
    '    at tryCatch (/var/task/node_modules/regenerator-runtime/runtime.js:63:40)\n' +
    '    at Generator.invoke [as _invoke] (/var/task/node_modules/regenerator-runtime/runtime.js:294:22)\n' +
    '    at Generator.next (/var/task/node_modules/regenerator-runtime/runtime.js:119:21)\n' +
    '    at asyncGeneratorStep (/var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)\n' +
    '    at _next (/var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)\n' +
    '    at /var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7\n' +
    '    at new Promise (<anonymous>)\n' +
    '    at /var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12',
  name: 'TypeError'
}
2022-05-16T08:42:55.886Z    0212a91e-aa6a-4dd1-b62c-bddaba2f6a39    ERROR   [next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
https://next-auth.js.org/errors#oauth_callback_handler_error Cannot read property 'findUnique' of undefined TypeError: Cannot read property 'findUnique' of undefined
    at getUserByAccount (/var/task/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45)
    at _callee2$ (/var/task/node_modules/next-auth/core/errors.js:315:29)
    at tryCatch (/var/task/node_modules/regenerator-runtime/runtime.js:63:40)
    at Generator.invoke [as _invoke] (/var/task/node_modules/regenerator-runtime/runtime.js:294:22)
    at Generator.next (/var/task/node_modules/regenerator-runtime/runtime.js:119:21)
    at asyncGeneratorStep (/var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at /var/task/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12 {
  name: 'GetUserByAccountError',
  code: undefined
}
// [...nextauth].js
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
});
// schema.prisma
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["referentialIntegrity"]
}

datasource db {
  provider             = "mysql"
  url                  = env("DATABASE_URL")
  referentialIntegrity = "prisma"
}

model Article {
  id         Int      @id @default(autoincrement())
  authorId   String
  author     User     @relation(fields: [authorId], references: [id])
  title      String   @db.VarChar(30)
  content    String   @db.Text
  excerpt    String   @db.VarChar(280)
  hashtags   String   
  published  Boolean  @default(false)
  isPrivate  Boolean  @default(false)
  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?  @db.Text
  access_token       String?  @db.Text
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?  @db.Text
  session_state      String?

  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)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  article       Article[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

Please help me!

ilyandho commented 2 years ago

I had the same issue but I had forgotten to run npx prisma migrate dev --name init after which everything ran well.

emmalegend commented 1 year ago

Hi good morning, still having this same issue..

//schema.prisma

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

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

}

model Account {
  id  String  @id @default(auto()) @map("_id") @db.ObjectId
  userId             String 
  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?

  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
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

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

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

  @@unique([identifier, token])
}

//[...nextauth].ts

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
});

//Error

[next-auth][error][adapter_error_getUserByAccount] 
https://next-auth.js.org/errors#adapter_error_getuserbyaccount 
Invalid `p.account.findUnique()` invocation in
/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }` {
  message: '\n' +
    'Invalid `p.account.findUnique()` invocation in\n' +
    '/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45\n' +
    '\n' +
    '   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),\n' +
    '   9 async getUserByAccount(provider_providerAccountId) {\n' +
    '  10     var _a;\n' +
    '→ 11     const account = await p.account.findUnique(\n' +
    'Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }`',
  stack: 'Error: \n' +
    'Invalid `p.account.findUnique()` invocation in\n' +
    '/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45\n' +
    '\n' +
    '   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),\n' +
    '   9 async getUserByAccount(provider_providerAccountId) {\n' +
    '  10     var _a;\n' +
    '→ 11     const account = await p.account.findUnique(\n' +
    'Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }`\n' +
    '    at RequestHandler.handleRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31955:13)\n' +
    '    at RequestHandler.handleAndLogRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31913:12)\n' +
    '    at /Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32458:25\n' +
    '    at async PrismaClient._executeRequest (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:33022:22)\n' +
    '    at async PrismaClient._request (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32994:16)\n' +
    '    at async getUserByAccount (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29)',
  name: 'Error'
}
[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
https://next-auth.js.org/errors#oauth_callback_handler_error 
Invalid `p.account.findUnique()` invocation in
/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }` Error: 
Invalid `p.account.findUnique()` invocation in
/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }`
    at RequestHandler.handleRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31955:13)
    at RequestHandler.handleAndLogRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31913:12)
    at /Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32458:25
    at async PrismaClient._executeRequest (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:33022:22)
    at async PrismaClient._request (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32994:16)
    at async getUserByAccount (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29) {
  name: 'GetUserByAccountError',
  code: undefined
}

Please help

bassem97 commented 1 year ago

hello, i have the same problem too !!! HELLP !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

krishnaUIDev commented 1 year ago

hello, i have the same problem too !!! HELLP !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Try this npx prisma migrate dev --name init

bassem97 commented 1 year ago

hello, i have the same problem too !!! HELLP !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Try this npx prisma migrate dev --name init

I tried many times, the problem still persist

bassem97 commented 1 year ago

problem solved by modifying prisma schema to this:


model User {
  id                    String     @id @default(uuid())
  name                  String
  email                 String?    @unique
  emailVerified         DateTime?   @map("email_verified")
  image                 String?
  createdAt             DateTime   @default(now())
  updatedAt             DateTime   @updatedAt
  accounts              Account[]
  sessions              Session[]
  @@map("users")
}
model Account {
  id                 String    @id @default(cuid())
  userId              String    @map("user_id")
  type                 String?
  provider           String
  providerAccountId  String    @map("provider_account_id")
  token_type         String?
  refresh_token      String?   @db.Text
  access_token       String?   @db.Text
  expires_at         Int?
  scope              String?
  id_token           String? @db.Text
  createdAt          DateTime  @default(now())
  updatedAt          DateTime  @updatedAt
  user               User      @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
  @@map("accounts")
}

model Session {
  id           String   @id @default(cuid())
  userId       String?  @map("user_id")
  sessionToken String   @db.Text @map("session_token") @unique
  accessToken  String?  @db.Text @map("access_token")
  expires      DateTime
  user         User?     @relation(fields: [userId], references: [id], onDelete: Cascade)
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  @@map("sessions")
}

model VerificationRequest {
  id         String   @id @default(cuid())
  identifier String
  token      String   @unique
  expires    DateTime
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@unique([identifier, token])
}

then execute npx prisma db push to apply schema changes to remote db

ethanniser commented 1 year ago

This fixed for me (using google oauth + planetscale mysql) thanks

ignaprados commented 1 year ago

Thanks @bassem97, it works!!

bassem97 commented 1 year ago

Thanks @bassem97, it works!!

Glad to hear 😍

payamsaremi commented 1 year ago

@bassem97 I have tried your solution but I get this error, and I need my user. will tis really drop the User table? or it's a false message?

You are about to drop the User table, which is not empty (11 rows).

frank1003A commented 1 year ago

@emmalegend were you able to resolve this ?

Hi good morning, still having this same issue..

//schema.prisma

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

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

}

model Account {
  id  String  @id @default(auto()) @map("_id") @db.ObjectId
  userId             String 
  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?

  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
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

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

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

  @@unique([identifier, token])
}

//[...nextauth].ts

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
});

//Error

[next-auth][error][adapter_error_getUserByAccount] 
https://next-auth.js.org/errors#adapter_error_getuserbyaccount 
Invalid `p.account.findUnique()` invocation in
/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }` {
  message: '\n' +
    'Invalid `p.account.findUnique()` invocation in\n' +
    '/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45\n' +
    '\n' +
    '   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),\n' +
    '   9 async getUserByAccount(provider_providerAccountId) {\n' +
    '  10     var _a;\n' +
    '→ 11     const account = await p.account.findUnique(\n' +
    'Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }`',
  stack: 'Error: \n' +
    'Invalid `p.account.findUnique()` invocation in\n' +
    '/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45\n' +
    '\n' +
    '   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),\n' +
    '   9 async getUserByAccount(provider_providerAccountId) {\n' +
    '  10     var _a;\n' +
    '→ 11     const account = await p.account.findUnique(\n' +
    'Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }`\n' +
    '    at RequestHandler.handleRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31955:13)\n' +
    '    at RequestHandler.handleAndLogRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31913:12)\n' +
    '    at /Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32458:25\n' +
    '    at async PrismaClient._executeRequest (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:33022:22)\n' +
    '    at async PrismaClient._request (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32994:16)\n' +
    '    at async getUserByAccount (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29)',
  name: 'Error'
}
[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
https://next-auth.js.org/errors#oauth_callback_handler_error 
Invalid `p.account.findUnique()` invocation in
/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }` Error: 
Invalid `p.account.findUnique()` invocation in
/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
Raw query failed. Code: `unknown`. Message: `Server selection timeout: No available servers. Topology: { Type: ReplicaSetNoPrimary, Servers: [ { Address: ac-nymnfql-shard-00-02.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-01.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, { Address: ac-nymnfql-shard-00-00.k1eh2av.mongodb.net:27017, Type: Unknown, Error: unexpected end of file }, ] }`
    at RequestHandler.handleRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31955:13)
    at RequestHandler.handleAndLogRequestError (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:31913:12)
    at /Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32458:25
    at async PrismaClient._executeRequest (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:33022:22)
    at async PrismaClient._request (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@prisma/client/runtime/index.js:32994:16)
    at async getUserByAccount (/Users/macintoshhd/Desktop/MERN/nextjs/imessage/frontend/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29) {
  name: 'GetUserByAccountError',
  code: undefined
}

Please help

mcnaveen commented 1 year ago

Everything was working fine. All of a sudden, I'm facing the same issue. Not sure how to solve it. I'm using Google, and Email Magic Link login.

frank1003A commented 1 year ago

Everything was working fine. All of a sudden, I'm facing the same issue. Not sure how to solve it. I'm using Google, and Email Magic Link login.

Found out that this issue is related to #2803|Linking accounts.

bassem97 commented 1 year ago

Thanks @bassem97, it works!

just save you user and press Y

CloudCodesStuff commented 1 year ago

@bassem97 im stilling getting an error with your schema, it says Error: foreign key constraints are not allowed, see https://vitess.io/blog/2021-06-15-online-ddl-why-no-fk/ 0: sql_schema_connector::apply_migration::migration_step with step=AddForeignKey { foreign_key_id: ForeignKeyId(0) } at schema-engine\connectors\sql-schema-connector\src\apply_migration.rs:21 1: sql_schema_connector::apply_migration::apply_migration at schema-engine\connectors\sql-schema-connector\src\apply_migration.rs:10 2: schema_core::state::SchemaPush at schema-engine\core\src\state.rs:441

itsjavi commented 1 year ago

I had this issue when using prisma + neon postgresql DB the problem was in my schema. I fixed it after changing the User email from this:

email            String?           @unique @db.VarChar(255)

to this:

email            String?           @unique

Now the column is of type text instead of varchar. It seems it had issues with that.

Also make sure that the bouncer connection urls have the &pgbouncer=true parameter

iiiok commented 1 year ago

Try run [npx prisma db push] to test Ur Prisma connect first. If Ur Prisma returns DNS error:[An error occured during DN5 resolution: no record found for name] then, it is a firewall issue. It cost me days to figure that out.

currenthandle commented 1 year ago

This seems to work for me as well! Thanks a lot 🙏

@bassem97 can you please provide some more context as to what you did and why/how this resolves the issue? Specifically, why does this schema.prisma (the one your provided) work and the implementation provided in the official documentation does not? https://authjs.dev/reference/adapter/prisma

Thank you!

problem solved by modifying prisma schema to this:

model User {
  id                    String     @id @default(uuid())
  name                  String
  email                 String?    @unique
  emailVerified         DateTime?   @map("email_verified")
  image                 String?
  createdAt             DateTime   @default(now())
  updatedAt             DateTime   @updatedAt
  accounts              Account[]
  sessions              Session[]
  @@map("users")
}
model Account {
  id                 String    @id @default(cuid())
  userId              String    @map("user_id")
  type                 String?
  provider           String
  providerAccountId  String    @map("provider_account_id")
  token_type         String?
  refresh_token      String?   @db.Text
  access_token       String?   @db.Text
  expires_at         Int?
  scope              String?
  id_token           String? @db.Text
  createdAt          DateTime  @default(now())
  updatedAt          DateTime  @updatedAt
  user               User      @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
  @@map("accounts")
}

model Session {
  id           String   @id @default(cuid())
  userId       String?  @map("user_id")
  sessionToken String   @db.Text @map("session_token") @unique
  accessToken  String?  @db.Text @map("access_token")
  expires      DateTime
  user         User?     @relation(fields: [userId], references: [id], onDelete: Cascade)
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  @@map("sessions")
}

model VerificationRequest {
  id         String   @id @default(cuid())
  identifier String
  token      String   @unique
  expires    DateTime
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@unique([identifier, token])
}

then execute npx prisma db push to apply schema changes to remote db

bassem97 commented 1 year ago

This seems to work for me as well! Thanks a lot 🙏

@bassem97 can you please provide some more context as to what you did and why/how this resolves the issue? Specifically, why does this schema.prisma (the one your provided) work and the implementation provided in the official documentation does not? https://authjs.dev/reference/adapter/prisma

Thank you!

problem solved by modifying prisma schema to this:

model User {
  id                    String     @id @default(uuid())
  name                  String
  email                 String?    @unique
  emailVerified         DateTime?   @map("email_verified")
  image                 String?
  createdAt             DateTime   @default(now())
  updatedAt             DateTime   @updatedAt
  accounts              Account[]
  sessions              Session[]
  @@map("users")
}
model Account {
  id                 String    @id @default(cuid())
  userId              String    @map("user_id")
  type                 String?
  provider           String
  providerAccountId  String    @map("provider_account_id")
  token_type         String?
  refresh_token      String?   @db.Text
  access_token       String?   @db.Text
  expires_at         Int?
  scope              String?
  id_token           String? @db.Text
  createdAt          DateTime  @default(now())
  updatedAt          DateTime  @updatedAt
  user               User      @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
  @@map("accounts")
}

model Session {
  id           String   @id @default(cuid())
  userId       String?  @map("user_id")
  sessionToken String   @db.Text @map("session_token") @unique
  accessToken  String?  @db.Text @map("access_token")
  expires      DateTime
  user         User?     @relation(fields: [userId], references: [id], onDelete: Cascade)
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  @@map("sessions")
}

model VerificationRequest {
  id         String   @id @default(cuid())
  identifier String
  token      String   @unique
  expires    DateTime
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@unique([identifier, token])
}

then execute npx prisma db push to apply schema changes to remote db

I dunno why the NextAuth documentation isn't updated , but it seems like next team forgot to apply the new prisma rules or something, like the attribut providerAccountId in Account table should be mapped in the db like this "provided_account_id" and the sessionToken and so on, hope they fix it asap

currenthandle commented 1 year ago

@bassem97 I'm happy to make a PR to the next-auth docs, unless you want to do it, lmk: https://github.com/nextauthjs/next-auth/blob/d73812bce5f5dc2f3f8b839554fc66a41284be30/packages/adapter-prisma/src/index.ts#L45

I'm curious though if not the docs, where did you find or how did you work out this alternate (and functional) implementation? Obviously, you are correct, because your code works 😊 But I'm curious how/where you found this eg: "attribut providerAccountId in Account table should be mapped in the db like this "provided_account_id" and the sessionToken and so on" if not in the docs.

Thanks again!

bassem97 commented 1 year ago

@bassem97 I'm happy to make a PR to the next-auth docs, unless you want to do it, lmk: https://github.com/nextauthjs/next-auth/blob/d73812bce5f5dc2f3f8b839554fc66a41284be30/packages/adapter-prisma/src/index.ts#L45

I'm curious though if not the docs, where did you find or how did you work out this alternate (and functional) implementation? Obviously, you are correct, because your code works 😊 But I'm curious how/where you found this eg: "attribut providerAccountId in Account table should be mapped in the db like this "provided_account_id" and the sessionToken and so on" if not in the docs.

Thanks again!

Yes please, let me do it. Actually i found it on my own, it took me barely 2 days of debugging and investigating about the real source of the error, and here we are. You're welcome dude 😁

currenthandle commented 1 year ago

@bassem97 Will do. When you say you "found it on [your] own." Where did you find it? I imagine not just trial and error lol. Curious what resources your looking at. Maybe I can learn something from your process 💪