0

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.

4
  • What is the error you encountered? Commented Mar 3, 2024 at 20:20
  • error in profile snippet & callback snippet which important to Role based auth in next-auth Commented Mar 3, 2024 at 20:49
  • What is your next auth route? If you are using app directory, it should be app/api/auth/[...nextauth]/route.ts. Rename it, and it shall work fine. Commented Mar 7, 2024 at 19:09
  • Share the error log or screenshot. Commented Nov 9, 2024 at 19:25

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

4 Comments

im using app router so changing that to /[...nextauth].js may led to another error by redirecting signin page to /app/api/auth/error url i think.
i am also using app router and this works fine with me.
when i rename that and click sign in button it redirect me to localhost:3000/api/auth/error? so it's led to another error.
@AdhishtanakaKulasooriya try this path .../[...nextauth]/route.js. then check if solves the issue. I have implemented this and it works. /../auth/error or /../auth/log and other routes will go inside [...nextauth] and will be hadnled by next-auth automatically. For more detail info check this answer stackoverflow.com/a/79172268/9308731 (you can avoid adapter implemntation)
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.