Search code examples
mongodbmaterial-uinext.jsadapternext-auth

Using Mongodb Adapter in NextAuth not working


I git clone & copy MUI Nextjs example project & start from there.

From NextAuth portal, they said I can just copy mongodb adapter setup here and basically it will work well out of the box. I placed this file in this path: /src/lib/mongodb.js

Here I'm using CredentialsProvider. Basically I'm using my own form for login & authentication process.

Here my /pages/api/auth/[...nextauth].js file:

import { MongoDBAdapter } from "@next-auth/mongodb-adapter";
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import clientPromise from "../../../src/lib/mongodb";

export default NextAuth({
  secret: process.env.SECRET,
  adapter: MongoDBAdapter(clientPromise),
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        const { email, password } = credentials

        if(email !== '[email protected]' || password !== 'password123') {
          throw new Error('User does not exists. Please make sure you insert the correct email & password.')
        }

        return {
          id: 1,
          name: 'Tester',
          email: '[email protected]'
        }
      }
    })
  ],
  callbacks: {
    redirect: async ({ url, baseUrl }) => {
      return baseUrl
    }
  }
})

What I understood, I can just straight away use this adapter & it will create 4 models/tables (User, Session, Account, VerificationToken) by default. So I don't need to create them myself. Ref doc here

According to the NextAuth MongoDB Adapter documentation, I just need to specify the MONGODB_URI in .env.local.

so here my /.env.local file content:

NEXTAUTH_URL=http://localhost:3000
MONGODB_URI=mongodb+srv://<username>:<password>@rest.lvnpm.mongodb.net/<database_name>?retryWrites=true&w=majority
SECRET=someSecret
NODE_ENV=development

So currently, it does nothing at all. I don't need to specify session.strategy to database since by default NextAuth will recognized that if I use adapter option.

What do I need to do here to make this work? Any helps is appreciated. Here my github project


Solution

  • I just found out that in NextAuth, if I use CredentialsProvider. I won't be able to persist data using database strategy. You may go here to NextAuth documentation itself to know why