Santhosh
Santhosh

Reputation: 53

Error while using the callbacks option in Next-auth

I'm trying to send the custom session from the Next-Auth to my client side. My app/api/auth/[...nextauth]/route.js Looks like,

import { MongoClient } from "mongodb";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
import NextAuth from "next-auth/next";

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "email", placeholder: "Email" },
        password: {
          label: "Password",
          type: "password",
          placeholder: "Password",
        },
      },
      async authorize(credentials, req) {
        try {
          const client = await MongoClient.connect(process.env.MONGO_URL, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
          });
          const db = client.db("test");
          const user = await db
            .collection("users")
            .findOne({ email: credentials.email });

          if (!user) throw new Error("User is not found!");

          if (user) {
            const checkPassword = await bcrypt.compare(
              credentials.password,
              user.password
            );
            if (!checkPassword) throw new Error("Password is incorrect!");
          }

          return {
            id: 1,
            name: user.name,
          };
        } catch (error) {
          throw new Error(error);
        }
      },
    }),
  ],
  callbacks: {
    async session({ session, user }) {
      session.user.name = user.name;
      session.user.id = user._id;
      session.user.username = user.username;

      return session;
    },
  },
};

const handler = NextAuth(authOptions);
export { handler as POST, handler as GET };

Here in callbacks, I'm trying to assign the session values with the user that I got above from the MongoDB. But it returns null. How to use the user I got from the MongoDB to assign the values fro session in Callbacks ?

Upvotes: 0

Views: 512

Answers (1)

chaffa
chaffa

Reputation: 81

Example for adding extra data (user role) session data were taken from token you must add jwt callback like in this exemple

callbacks: {
    async jwt({ token, user }) {
      /* Step 1: update the token based on the user object */

      if (user) {
        token.role = user.role;
      }
      return token;
    },
    async session({ session, token }) {
      /* Step 2: update the session.user based on the token object */
      console.log({ session, token });
      if (token && session.user) {
        session.user.role = token.role;
        
      }
      return session;
    },
  },

Upvotes: 0

Related Questions