I’m currently working on implementing role-based authentication using NextAuth.js in my Next.js application. I’ve followed the documentation provided by NextAuth.js, but I encountered an error(in profile snippet and callback snippet which i copied from next-auth documentation) when trying to add role-based authentication to my API routes.
I’m using TypeScript and my API route file is located at pages/api/auth/[..nextauth]/route.ts.
import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import {signInWithEmailAndPassword} from 'firebase/auth';
import auth from '@/app/lib/auth';
export const authOptions = {
secret: process.env.AUTH_SECRET,
pages: {
signIn: '/signin'
},
session: {
strategy: "jwt" as const,
maxAge: 3600,
},
providers: [
CredentialsProvider({
//error
profile(profile) {
return {
role: profile.role ?? "user",
}
},
name: 'Credentials',
credentials: {},
async authorize(credentials): Promise<any> {
return await signInWithEmailAndPassword(auth, (credentials as any).email || '', (credentials as any).password || '')
.then(userCredential => {
if (userCredential.user) {
return userCredential.user;
}
return null;
})
.catch(error => (console.log(error)))
.catch((error) => {
console.log(error);
});
}
})
],
//error
callbacks: {
async jwt({ token, user }) {
if (user) token.role = user.role;
return token;
},
async session({ session, token }) {
if (session?.user) session.user.role = token.role;
return session;
},
},
}
const handler = NextAuth(authOptions)
export { handler as GET, handler as POST}
Could someone please help me understand why this error is happening and how I can properly implement role-based authentication with NextAuth.js in my API routes?
What I Tried:
-
Using NextAuth.js Documentation: I’m setting up role-based authentication in my Next.js app by following the NextAuth.js documentation.
-
Copying Code: I copied code snippets from the documentation to implement role-based authentication.
-
Encountering Error: After implementing the code, I encountered an error.
2
Answers
if you are using nextjs version 14 you need the next auth file route like this — "pages/api/auth/[…nextauth].js". maybe that will solve the issue.
link for the documentataion: click here
my auth otpions in pages/api/auth/[…nextauth].ts — if you using ts make the […nextauth] file typescript. works like charm for me