skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. import { PrismaAdapter } from "@next-auth/prisma-adapter";
    import NextAuth, { AuthOptions } from "next-auth";
    import CredentialsProvider from "next-auth/providers/credentials";
    import { error } from "console";
    import bcrypt from "bcrypt";
    import { db } from "@/lib/prismadb";
    
    export const authOptions: AuthOptions = {
      adapter: PrismaAdapter(db),
      providers: [
        CredentialsProvider({
          name: "credentials",
          credentials: {
            email: { label: "email", type: "email" },
            password: { label: "password", type: "password" },
          },
          async authorize(credentials) {
            if (!credentials?.email || !credentials?.password) {
              throw new Error("invalid credentials");
            }
    
            const user = await db.user.findUnique({
              where: {
                email: credentials.email,
              },
            });
    
            if (!user || !user?.password) {
              throw new Error("invalid credentials");
            }
    
            const isCorrect = await bcrypt.compare(
              credentials.password,
              user.password
            );
    
            if (!isCorrect) {
              throw new Error("invalid credentials");
            }
    
            return user;
          },
        }),
      ],
      pages: {
        signIn: "/",
      },
      debug: process.env.NODE_ENV === "development",
      session: {
        strategy: "jwt",
      },
      secret: process.env.NEXTAUTH_SECRET,
    };
    
    export default NextAuth(authOptions);
    

    my auth otpions in pages/api/auth/[…nextauth].ts — if you using ts make the […nextauth] file typescript. works like charm for me

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search