Exploring the functionalities of using next-auth with GitHub and Prisma

Currently in the process of setting up next auth to integrate with GitHub as a provider. Here is an overview of my setup:

[...nextauth].js

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

const prisma = new PrismaClient()

export default NextAuth({
    // Configure one or more authentication providers
    providers: [
        Providers.GitHub({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
        }),
        Providers.Email({
            server: process.env.EMAIL_SERVER,
            from: process.env.EMAIL_FROM,
        }),
    ],
    adapter: PrismaAdapter(prisma),
})

This is how my prisma schema is structured:

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

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

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?

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

After successfully connecting to GitHub and authorizing the application, I encounter this error:

[next-auth][error][prisma__get_user_by_provider_account_id_error]
https://next-auth.js.org/errors#prisma__get_user_by_provider_account_id_error PrismaClientValidationError:
Invalid `prisma.account.findUnique()` invocation:

{
  where: {
    providerId_providerAccountId: {
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      providerId: 'github',
      providerAccountId: 13868008
    }
  },
  select: {
    user: true
  }
}

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


    at Document.validate (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:35195:19)
    at PrismaClient._executeRequest (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37530:17)
    at consumer (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37475:23)
    at C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37477:47
    at AsyncResource.runInAsyncScope (async_hooks.js:189:9)
    at PrismaClient._request (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37477:25)
    at request (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37580:77)
    at Object.then (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37595:22)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  clientVersion: '2.30.3'
}
[next-auth][error][oauth_callback_handler_error]
https://next-auth.js.org/errors#oauth_callback_handler_error Error:
Invalid `prisma.account.findUnique()` invocation:

{
  where: {
    providerId_providerAccountId: {
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      providerId: 'github',
      providerAccountId: 13868008
    }
  },
  select: {
    user: true
  }
}

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


    at Document.validate (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:35195:19)
    at PrismaClient._executeRequest (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37530:17)
    at consumer (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37475:23)
    at C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37477:47
    at AsyncResource.runInAsyncScope (async_hooks.js:189:9)
    at PrismaClient._request (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37477:25)
    at request (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37580:77)
    at Object.then (C:\Users\tfr\Projects\employee-nextjs-gitlab\node_modules\@prisma\client\runtime\index.js:37595:22)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  name: 'GetUserByProviderAccountIdError'
}

Seeking guidance on what may be going wrong here. Appreciate any assistance.

Answer №1

If you're looking to make some changes to the Prisma scheme, consider updating it as follows:

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

The current Nexth Auth Prisma adapter is experiencing some technical issues. For more details, refer to the following link: https://github.com/nextauthjs/next-auth/issues/3815

Answer №2

The value of providerAccountId should be a string in the schema.prisma file. It appears that you are passing a number instead, which may be causing the error to occur.

Answer №3

I recently tackled a problem and successfully resolved it. The issue was fixed by adding @@map("accounts") in the Account schema. Furthermore, each User collection can only have one account, which is either Github or Google SignIn for the user. If a user is already logged in through Google, attempting Github authentication will result in an error.

Below is my Prisma schema file:

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

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

model Account {
  id                 String @id @default(auto()) @map("_id") @db.ObjectId
  userId             String @db.ObjectId
  type               String
  provider           String
  providerAccountId  String  @map("provider_account_id")
  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])
  @@map("accounts")
}

model User {
  id              String @id @default(auto()) @map("_id") @db.ObjectId
  name            String?
  email           String?   @unique
  emailVerified   DateTime?
  image           String?
  hashedPassword  String?
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
  favoriteIds     String[] @db.ObjectId

  accounts        Account[]
  listings        Listing[]
  reservations    Reservation[]
}

model Listing {
  id              String @id @default(auto()) @map("_id") @db.ObjectId
  title           String
  description     String
  imageSrc        String
  createdAt       DateTime @default(now())
  category        String
  roomCount       Int
  bathroomCount   Int
  guestCount      Int
  locationValue   String
  userId          String @db.ObjectId
  price           Int

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

model Reservation {
  id              String @id @default(auto()) @map("_id") @db.ObjectId
  userId          String @db.ObjectId
  listingId       String @db.ObjectId  
  startDate       DateTime
  endDate         DateTime
  totalPrice      Int
  createdAt       DateTime @default(now())

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styled-components does not generate a style tag as output

After creating a new project in React with Webpack, I decided to experiment with Styled Components. In my index.js file, the code is structured like this: import React from "react" import ReactDOM from "react-dom" import Page from "./site/Page" import s ...

Is there a way to display a different file, such as index.html, based on the screen width?

I'm facing an issue. I have completed a web page (with HTML, CSS, and JavaScript), but now I want to create a mobile version using different HTML files, another index.html file, and a separate CSS file. What changes do I need to make in the main page ...

What are the fundamentals of type conversion in struts2?

In my struts.xml file, I have the following code: <s:textfield id="thresholdParameter_1" name="gmathreshold.distinctBnumberRatio"> </s:textfield></td> The gmathreshold is a bean with a member variable distinctBnumberRatio which is a ...

Uncovering the array within Javascript

I'm struggling to figure out why I can't access an array that PHP sends back to me. When AJAX makes a call, I send back this: $response['success'] = true; In my PHP file, I use echo json_encode($response); to send it. However, when I ...

Handler for stack trace errors and error handling for promises

Introducing my customized error handling function: function onError(message, source, lineno, colno, error) { sendRequestToSendMail(arguments) } window.onerror = onError In addition to that, I have asynchronous tasks utilizing promises and I aim to captur ...

Messaging services are currently unavailable

Having trouble integrating FCM with my Next.js project. Whenever I try to save the firebase.js config file, I encounter an error. Struggling to use Firebase Cloud Messaging in Firebase V9. Current version of firebase being used: 9.10.0 https://i.sstatic.n ...

Exploring and storing nested data structures in JavaScript/jQuery arrays

While I've come across various inquiries regarding the conversion of an array or object into a nested list, I have only managed to find one relevant question that addresses my specific issue. Despite attempting different methods to access the children ...

React encountered an error: Unable to destructure the property 'id' of '_ref' as it has been defined

After spending several hours trying to solve this issue, I am completely stuck. The console shows that the patch request successfully updates the information, but then my map function breaks, leading to a blank page rendering. Here is the problematic comp ...

Having trouble retrieving state parameters when trying to launch a modal in AngularJS

When the "view detail" link is clicked, I wanted to open a modal for a detailed view of a specific user. However, I encountered an issue where I couldn't retrieve the user ID in the resolve attribute of $uibModal.open(). Strangely enough, the ID is av ...

Numbering updated on pagination

Is there a way to achieve this? I currently have a pagination script that pulls data from a mysql database via php and uses jquery for functionality. I am interested in incorporating a filter into the pagination system, allowing users to remove certain c ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

Having trouble with Stripe Checkout? Encountering a 404 error when attempting to use the Next.js App

I have been working on integrating a simple Stripe checkout into a Next.js App router. The code functions properly when using the pages router in Next.js, but I encounter a 404 error - 'This page could not be found' when I try to use it in the Ap ...

JavaScript text spacing

I'm currently utilizing the JavaScript code snippet below to clear out the existing content within a div element in order to insert new elements. However, I've encountered an issue where once the div is cleared, its CSS styling is lost. I am atte ...

Oops! It appears that there is an error saying "Data.filter is not a function"

I've encountered an issue where I pass a prop from parent to child and then return it, resulting in a 'filter is not a function' error. Any assistance in identifying the cause of this error would be greatly appreciated. Here is the array th ...

Adjust the height of the floating div to completely occupy the space below it

I have multiple DIVs within my content container, some floating to the right and others to the left on screens larger than 400px. See working example here: https://jsfiddle.net/cmbpt1hd/ I need the height of area-three to automatically adjust so it fills ...

During the installation process of Next JS, I faced a challenge that hindered

While setting up NextJS, I ran into the following issue: D:\Codes\React\Learn>npx create-next-app npm WARN using --force Recommended protections disabled. npm WARN using --force Recommended protections disabled. npm ERR! code E404 npm ERR ...

What is the best method to obtain the user id within a Redux action?

I am striving to display only user-related items, so I am attempting to retrieve items by sending a request for data to the user id /api/items/:userid. Utilizing Redux store in this process. Here is my server-side code snippet: router.get("/:userid", (req ...

A guide to injecting HTML banner code with pure Vanilla Javascript

Looking for a solution to incorporate banner code dynamically into an existing block of HTML on a static page without altering the original code? <div class="wrapper"><img class="lazyload" src="/img/foo01.jpg"></div> <div class="wrapp ...

Converting Variable Values to Element IDs in JavaScript: A Helpful Guide

Is it possible to declare a value in variable A and then access that value as an id in variable B using the method getElementById()? var A = 10; var B = document.getElementById(A); console.log(B); ...

"What's the best way to update the src attribute of an iFrame when a user clicks

I'm new to coding in PHP or JavaScript, so please bear with me if my question isn't quite right. I'm looking for a way to dynamically pass and embed a URL from a link into the src attribute of an iframe. Essentially, I want users to click o ...