codingIsLove
codingIsLove

Reputation: 121

"GetUserByAccountError" when using Nextjs 13.4, next-auth ^4.22.1 and @next-auth/prisma-adapter ^1.0.6

What causes the GetUserByAccountError when trying to login via SocialLogin using Github or Google? Here is the error in more detail:

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

 Error:
Invalid `prisma.account.findUnique()` invocation:

{
  where: {
    provider_providerAccountId: {
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
      providerAccountId: '100794952997699653180',
      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?: AccountProviderId_providerAccountIdCompoundUniqueInput
}


    at Ai.validate (C:\Users\Heiner\chatgpt\frontend\node_modules\@prisma\client\runtime\library.js:144:73)
    at un.createMessage (C:\Users\Heiner\chatgpt\frontend\node_modules\@prisma\client\runtime\library.js:161:1298)
    at C:\Users\Heiner\chatgpt\frontend\node_modules\@prisma\client\runtime\library.js:174:10818
    at Object.runInChildSpan (C:\Users\Heiner\chatgpt\frontend\node_modules\@prisma\client\runtime\library.js:171:1343)       
    at t._executeRequest (C:\Users\Heiner\chatgpt\frontend\node_modules\@prisma\client\runtime\library.js:174:10795)
    at async getUserByAccount (webpack-internal:///(sc_server)/./node_modules/@next-auth/prisma-adapter/dist/index.js:224:29) 
{
  name: 'GetUserByAccountError',
  code: undefined
}

Things I tried:

How to reproduce

In app/api/auth/[...nextauth]/route.ts:

import { Session } from "next-auth"
import NextAuth from "next-auth/next"
import GoogleProvider from "next-auth/providers/google"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import bcrypt from "bcrypt"
import GithubProvider from "next-auth/providers/github"
import CredentialsProvider from "next-auth/providers/credentials"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()

const handler = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GithubProvider({
      name: "github",
      clientId: process.env.GITHUB_CLIENT_ID as string,
      clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
    }),
    GoogleProvider({
      name: "google",
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
    CredentialsProvider({
      name: "credentials",
      credentials: {
        email: { label: "email", type: "email" },
        password: { label: "password", type: "password" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials?.password)
          throw new Error("Invalid credentials")

        try {
          const user = await prisma.user.findFirst({
            where: { email: credentials.email },
          })
          if (!user || !user?.hashedPassword)
            throw new Error("Invalid credentials")

          const isValid = await bcrypt.compare(
            credentials.password,
            user.hashedPassword
          )
          if (!isValid) throw new Error("Invalid credentials")
          return user
        } catch (e: any) {
          throw new Error("Invalid credentials")
        }
      },
    }),
  ],
  debug: process.env.NODE_ENV === "development",
  session: {
    strategy: "jwt",
  },
  secret: process.env.NEXTAUTH_SECRET as string,
})

export { handler as GET, handler as POST }

in schema.prisma:

// 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_URL")
}

model User {
  id             String    @id @default(cuid())
  name           String?
  hashedPassword String?
  email          String?   @unique
  emailVerified  DateTime?
  image          String?
  createdAt      DateTime  @default(now())
  updatedAt      DateTime  @updatedAt
  accounts       Account[]
  sessions       Session[]
  Post           Post[]
  Comment        Comment[]
  Like           Like[]

  @@map(name: "user")
}

model Post {
  id        Int       @id @default(autoincrement())
  image     String
  caption   String?
  createdAt DateTime  @default(now())
  userId    String
  user      User      @relation(fields: [userId], references: [id])
  comments  Comment[]
  likes     Like[]
}

model Comment {
  id        Int      @id @default(autoincrement())
  text      String
  createdAt DateTime @default(now())
  userId    String
  postId    Int
  user      User     @relation(fields: [userId], references: [id])
  post      Post     @relation(fields: [postId], references: [id])
}

model Like {
  id     Int    @id @default(autoincrement())
  userId String
  postId Int
  user   User   @relation(fields: [userId], references: [id])
  post   Post   @relation(fields: [postId], references: [id])
}

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], name: "providerId_providerAccountId")
  @@map(name: "account")
}

model Session {
  id           String   @id @default(cuid())
  userId       String
  expires      DateTime
  sessionToken String   @unique
  accessToken  String   @unique
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt
  user         User     @relation(fields: [userId], references: [id])
}

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, when choosing a gmail account for example, I will get GetUserByAccountError . I don't know why. It basically should work, or?

Upvotes: 2

Views: 543

Answers (1)

NateDavis
NateDavis

Reputation: 295

In the Account model, change providerId to provider.

https://authjs.dev/reference/adapter/prisma

Upvotes: 0

Related Questions