Next.js Discord

Discord Forum

Saved Session is not JWT Token, it's the User Object?

Unanswered
West African Lion posted this in #help-forum
Open in Discord
West African LionOP
Hey, it's my first time using NextAuth.js and I had a lot of problems when trying to implement it into NextJS_14.

I'm using Javascript + App Router.

Could anyone tell me if I have any mistakes here or if I understood something wrong.

[...nextauth]/route.js File
import NextAuth from 'next-auth';

import CredentialsProvider from "next-auth/providers/credentials";
import userModel from "@/models/User";
import dbConnect from "@/lib/dbConnect";
import bcrypt from "bcrypt";

dbConnect();

export const AuthOptions = {
    providers: [
        CredentialsProvider({
            async authorize(credentials) {
                try {
                    const { username, password } = credentials;

                    // Find the user in the database
                    const user = await userModel.findOne({ username });

                    if (user) {
                        // Compare the provided password with the hashed password in the database
                        const passwordMatch = await bcrypt.compare(password, user.password);

                        if (passwordMatch) {
                            // Return the user object
                            return user;
                        } else {
                            console.log("Password does not match");
                        }
                    }

                    // Return null if the user is not found or the password does not match
                    return null;
                } catch (e) {
                    console.log(e);
                    return null;
                }
            }
        })
    ],
    session: {
        strategy: "jwt",
        maxAge: 24 * 60 * 60, // 1 day
    },
    pages: {
        signIn: "/login",
    },
    secret: process.env.JWT_SECRET,
    debug: process.env.NODE_ENV === "development",
    callbacks: {
        async session({ session, token }) {
            session.user = token.user;

            // verify if session is still valid
            const user = await userModel.findById(token?.user?._id);

            if (!user) {
                return null;
            }

            // verify if password matches
            if (user.password !== token.user.password) {
                return null;
            }

            // verify if username matches
            if (user.username !== token.user.username) {
                return null;
            }

            return session;
        },
        async jwt({ token, user }) {
            if (user) {
                token.user = user;
            }
            return token;
        }
    }
};

const handler = NextAuth(AuthOptions);

export { handler as GET, handler as POST };



dashboard/page.js
"use client";

import { useSession } from "next-auth/react";
import { redirect } from "next/navigation";

export default function Dashboard() {
    const { data: session, status } = useSession();

    if (status === "loading") {
        return <p>Loading...</p>;
    }

    if (!session) {
        return redirect("/login");
    }

    return (
        <>
            <h1>Dashboard</h1>
            <p>Welcome {JSON.stringify(session)}</p>
        </>
    );
}

12 Replies

West African LionOP
Yeah I am unsure whether this is the correct way of using NextAuth, I have indeed read the documentation, but it didn't really help me understand if I have correctly implemented it.
yes it return you the user object
West African LionOP
Yeah, but I am unsure if this is the correct way to do it.
look good to me
West African LionOP
But is it a good Idea to also return the hashed password in the session?
@West African Lion But is it a good Idea to also return the hashed password in the session?
West African LionOP
Tho if I dont do that, I cannot check whether the password has changed or not
next-auth will omit it but you also can omit it before the return
West African LionOP
I dont think I understand
if (passwordMatch) {
                            // Return the user object
delete user.password
                            return user;
                        } else {
                            console.log("Password does not match");
                        }
                    }
then use a database session
instead of jwt strategy