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>
</>
);
}```