The integration of NextAuth Credential Provider with Prisma Adapter in the latest version of Next12 does not

I've configured my Nextjs (Next12) project with NextAuth CredentialsProvider and I'm using the Prisma Adapter to store user sessions in the database.

I followed the guidelines from the NextAuth team's documentation, but when I click on the login button, nothing happens.

Important Points

Prior to this:

  • I made sure that fetching data from the database was working correctly.
  • I also tried using just
    session: { jwt: true, maxAge: 30 * 24 * 60 * 60 }
    without incorporating the Adapter, and it worked fine as well.

Query

Now, I want to confirm whether it is feasible to combine CredentialsProvider with an Adapter at all?

NextAuth API

Below are examples of a working setup and a non-working one: /pages/api/auth/[...nextauth].js

  • Working: does not utilize an adapter
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    secret: process.env.SECRET,
    adapter: PrismaAdapter(prisma),
    session: {
      jwt: true,
      maxAge: 30 * 24 * 60 * 60, // 30 days
    }
    providers: [
      CredentialsProvider({
        async authorize(credentials) {
          const user = await prisma.user.findFirst({
            where: {
                email: credentials.email,
                password: credentials.password
            }
          });

          if (user !== null)
          {
              return user;
          }
          else {
            throw new Error('User does not exists. Please make sure you insert the correct email & password.')
          }
        }
      })
    ],
    callbacks: {
      redirect: async ({ url, baseUrl }) => {
        return baseUrl
      },
      jwt: async ({ token, user, account, profile, isNewUser }) => {
        if (typeof user !== typeof undefined) token.user = user;
  
        return token
      },
      session: async ({ session, user, token }) => {
        token?.user && (session.user = token.user)
  
        return session
      }
    }
  })
}
  • Not Working: utilizes prisma adapter
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from '@prisma/client';
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
const prisma = new PrismaClient()

export default async function auth(req, res) {
  return await NextAuth(req, res, {
    secret: process.env.SECRET,
    adapter: PrismaAdapter(prisma),
    providers: [
      CredentialsProvider({
        async authorize(credentials) {
          const user = await prisma.user.findFirst({
            where: {
                email: credentials.email,
                password: credentials.password
            }
          });

          if (user !== null)
          {
              return user;
          }
          else {
            throw new Error('User does not exists. Please make sure you insert the correct email & password.')
          }
        }
      })
    ],
    callbacks: {
      redirect: async ({ url, baseUrl }) => {
        return baseUrl
      },
      jwt: async ({ token, user, account, profile, isNewUser }) => {
        if (typeof user !== typeof undefined) token.user = user;
  
        return token
      },
      session: async ({ session, user, token }) => {
        token?.user && (session.user = token.user)
  
        return session
      }
    }
  })
}

Prisma Schema

Here is the provided schema.prisma (from the NextAuth documentation):-

  • I have already executed npx prisma migrate dev & npx prisma generate
// 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 = ["referentialIntegrity"]
}

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

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
  password      String?
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

Answer №1

After some research, I discovered that the integration of the CredentialsProvider from the package next-auth with the adapter is not feasible as indicated in this documentation. The reasons behind this limitation or why it is not advisable to use the CredentialsProvider are explained here.

For further insight into this issue, you can refer to this discussion thread.

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

The Cross-Origin Resource Sharing (CORS) problem doesn't seem to be evident when sending a Postman GET request to Passport.authenticate(), but Nextjs is encountering issues when trying

I've been working on implementing Google Login with a Next.js frontend and an Express.js backend. I followed this tutorial. Using the URL http://localhost:5200/auth/google, I expect to receive the same response as when using Postman: <title>Sig ...

Utilizing the `promise.all` object in a useState hook

Can anyone help me with setting up an object to use useState? I am working with the dataMap object that needs to be passed to the setResults function. Any assistance would be greatly appreciated! ? export default function Home() { const [results, setRe ...

Extracting the value from a Text Editor in React Js: [Code snippet provided]

Currently, I am in the process of developing a basic app that generates a JSON form. So far, I have successfully incorporated sections for basic details and employment information. The basic details section consists of two input fields: First Name and Las ...

I am encountering an error when trying to read the property 'getState' of undefined in Next.js with Redux and PersistGate

An error occurred while migrating from Create React App to Next. I am unable to use Redux and have tried multiple solutions without success. https://i.stack.imgur.com/gfOaE.png _app.js import "../styles/globals.css"; import App from "next/app"; import { ...

Unable to insert line breaks using " " or "<br>" in a textarea element

I'm struggling to insert a predefined string with line breaks into a <textarea> using React/NextJS. I've tried various methods, including using &#13; and <br>, but none seem to be effective: setTextAreaValue('a&#13;bc< ...

Node.js SQLite3 - DB.each() not running the subsequent code block

When running the code snippet below, I am getting the following output: var db = new sqlite3.Database("database.sqlite") console.log("2") db.each("SELECT * FROM gban WHERE id = '"+id+"'", async functi ...

What could be the reason the server actions in nextjs 13 are not functioning correctly?

I am currently working on a project to retrieve data from mockapi.io, a mock API. However, I am encountering an issue where the fetched data is not displaying in the browser. There are no visible errors, and the browser window remains blank. Interestingly, ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

The 'required' validator in Mongoose seems to be malfunctioning

I've been attempting to validate the request body against a Mongoose model that has 'required' validators, but I haven't been successful in achieving the desired outcome so far. My setup involves using Next.js API routes connected to Mo ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

Issue with the useSWR hook causing the DOM not to update correctly due to mutation

My next.js app is utilizing the `useSWR` hook to fetch and populate data. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus: false, }) The problem I am facing is that the DOM is not updating as expected after the `mu ...

The Next.js Image component is not compatible with an external URL as the image source

I've been struggling to use the image component in Next.js with an external URL as the source, but I keep encountering an error. I followed the instructions in the official Next.js documentation and updated the next.config.js file, but unfortunately, ...

The error message "Type 'null' cannot be assigned to type 'Element | DocumentFragment'" occurs when using Nextjs/React createPortal

I am completely new to typescript. Currently, I'm working on a project that has a lot of pre-configured react components in JavaScript files (.js). My task now is to convert everything to TypeScript (.tsx) without triggering any ESLint errors. Unfort ...

Cannot access Nextjs Query Parameters props within the componentDidMount() lifecycle method

I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

Customizing the HTMLElement class to modify particular attributes

Is there a way to modify the behavior of an HTMLElement's scrollTop property by adding some extra logic before updating the actual value? The common approach seems to be deleting the original property and using Object.defineProperty(): delete element. ...

Error: The integer provided in the Stripe payment form is invalid in the

I'm encountering an error that I can't seem to figure out. I believe I'm following the documentation correctly, but Stripe is not able to recognize the value. Have I overlooked something important here? https://stripe.com/docs/api/payment_i ...

Guide to leveraging a JWT token for API access in a server-side component with Next.js version 14

I am currently working on a login component for clients. Once the user logs in, the backend (built separately in NestJS) provides a jwt_token. I am then displaying all users on a server-side rendered page. How can I properly store this token and include it ...

Can you explain the distinct variations between these two approaches for obtaining API data?

When working with third-party APIs in NextJS 14, I encountered two different methods to query the API that resulted in slightly different outcomes. Method 1: Located within the /api folder as a route handler: export async function GET() { const res = aw ...

What is the process for integrating material symbols into a Next.js project?

I'm currently using Next.js version 13.2 and I am looking to integrate the material-symbols into my project. My goal is to utilize it in the following manner: <span className="material-symbols-rounded">face</span> Upon further ...