Home > Blockchain >  How to switch from passport.js express to Next.js with Mongoose?
How to switch from passport.js express to Next.js with Mongoose?

Time:03-26

I have an express server that uses passport and mongoose to store users. The user data changes frequently (number of payment-tokens, user name, verifying email address tokens), and the UI has to show these changes on every change.

I'm transitioning to Next.js and still trying to use the mongodb database to store users, sessions, etc. I want to keep it serverless, so I can't use an express server (although afaik it is possible).

I'm currently using Next-Auth with the Credentials provider, but it can't save user sessions in the db, so when my user data changes, it isn't reflected in the UI.

How do I solve this? Should I not use next-auth for this?

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

import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import authenticateUser from "../../../lib/authenticateUser";

export default NextAuth({
    providers: [
        CredentialsProvider({
            name: 'Login',
            credentials: {
                email: { label: 'E-mail', type: "email", placeholder: "[email protected]" },
                password: { label: 'Password', type: "password" }
            },
            async authorize(credentials, req) {
                const payload = {
                    email: credentials.email,
                    password: credentials.password,
                };
                const user = await authenticateUser(payload.email, payload.password);
                return user;
            }
        })
    ],
    secret: process.env.JWT_SECRET,
    callbacks: {
        jwt: async ({ token, user }) => {
            user && (token.user = user)
            return token
        },
        session: async ({ session, token }) => {
            session.user = token.user
            return session
        }
    },
    session: {
        strategy: 'jwt',
        maxAge: 1 * 24 * 60 * 60, // 1d
    },
    jwt: {
        secret: process.env.JWT_SECRET,
        encryption: true,
    },
})

CodePudding user response:

You should check out this repo which shows you how to do the integration between Next.js, Passport.js, and MongoDb.

The guide sections goes into step by step explanation. But please depend on the code because the guide might be slightly different and not updated to reflect the current code in the repo.

  • Related