Currently, I'm in the process of integrating role-based authentication using NextAuth.js into my Next.js application. Despite following the provided documentation meticulously, an error (in profile snippet and callback snippet which I copied from next-auth documentation) surfaced when attempting to introduce role-based authentication to my API routes.
I've opted for TypeScript, and my API route file can be found 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));
}
})
],
//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}
I would greatly appreciate it if someone could shed light on why this error is occurring and guide me on how to effectively implement role-based authentication with NextAuth.js in my API routes.
My Approach:
Utilizing NextAuth.js Documentation: I am configuring role-based authentication in my Next.js app by adhering to the guidance provided in the NextAuth.js documentation.
Duplicating Code: I replicated code snippets from the documentation to establish role-based authentication.
Facing Error: Upon implementing the code, I encountered an error.