Search code examples
mongodbauthenticationnext.jsoneloginnext-auth

Storing User data - NextAuth v3 with MongoDB


In my NextJS app, am trying to use MongoDB to store the User data that's being used by the Next-Auth (v3) package.

Code from my /api/auth/[...nextauth].js file:

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

export default NextAuth({
    providers: [
        Providers.OneLogin({
            clientId: process.env.ONELOGIN_CLIENT_ID,
            clientSecret: process.env.ONELOGIN_CLIENT_SECRET,
            domain: process.env.ONELOGIN_DOMAIN
        })
    ],

    callbacks: {
        
        jwt: async (token, user, account, profile, isNewUser) => {
            if (user) { //-- if success, store the id of the user in jwt token
                token.uid = user.id;
            }
           return Promise.resolve(token);
        },
        
        session: async (session, user) => {
            session.user.uid = user.uid;    //-- store the id of the user in the session data
            return Promise.resolve(session);
        }
    },
    
    // Optional SQL or MongoDB database to persist users
    database: process.env.MONGODB_URL
    // database: {
    //     type: "mongodb",
    //     useNewUrlParser: true,
    //     url: process.env.MONGODB_URL,
    // },
})

But it's always throwing the following error:

[next-auth][error][session_error] https://next-auth.js.org/errors#session_error Error: optional dependency [mongodb] found but version [4.1.2] did not satisfy constraint [^3.5.9]

I have already installed the mongodb package. Am unable to figure out the issue. My MongoDB url is working fine as it is able to do other database operations(like adding new data, fetching, etc.)


Solution

  • The issue is that major version of the dependency is different and considered breaking: "^3.5.9" will satisfy updates within v3. Your version of 4.1.2 will be considered out of range as changes to the major of 4 would be considered significant/breaking.

    package.json

     "peerOptionalDependencies": {
        "mongodb": "^3.5.9",
        "mysql": "^2.18.1",
        "mssql": "^6.2.1",
        "pg": "^8.2.1",
        "@prisma/client": "^2.16.1"
      }, 
    

    Update the mongodb version to support the change in major version i.e. "mongodb": "^3.5.9 || ^4", or "mongodb": "^4", etc

      "peerOptionalDependencies": {
        "mongodb": "^3.5.9 || ^4",
        "mysql": "^2.18.1",
        "mssql": "^6.2.1",
        "pg": "^8.2.1",
        "@prisma/client": "^2.16.1"
      },