Home > Back-end >  Next Auth Credentials Provider JWT / Session callback
Next Auth Credentials Provider JWT / Session callback

Time:04-26

I am having some difficulties passing my token to the session callback. My end goal is to send the logged-in users data to the client-side. Originally I was only sending back the users email, but now I would like to have the user's username and name sent along with the email. By following the docs, we have to pass the JWT and Session callback in order for us devs to have access to more data in a token. Currently, in my JWT callback, I am able to log the users data, great. Yet, when I try to log the data in the Session callback, I am getting an empty {}. Any tips are greatly appreciated. Thank you in advance.

import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";

// Helper Functions
import {
  connectToDatabase,
  comparePasswords,
} from "../../helper/HelperFunctions";

export default NextAuth({
  session: { jwt: true },
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        const client = await connectToDatabase();

        const userCollection = client.db().collection("users");

        const user = await userCollection.findOne({
          email: credentials.email,
        });

        // const userInfo = {
        //   firstName: user.firstName,
        //   lastName: user.lastName,
        //   email: user.email,
        //   userName: user.userName,
        // };

        // console.log(userInfo);

        if (!user) {
          client.close();

          throw new Error("No user found!");
        }

        const isValid = await comparePasswords(
          credentials.password,
          user.password
        );

        if (!isValid) {
          client.close();

          throw new Error("Invalid password");
        }

        client.close();

        if (user) {
          return {
            user,
          };
        } else {
          return null;
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      // Persist the OAuth access_token to the token right after signin
      if (user) {
        token = user;
        console.log(token);
        // all of the user data is being logged, yet how to pass it down to session callback so i can use all the user data in the client?
      }
      return token;
    },
  },
  async session({ session, token, user }) {
    session.user = token;
    console.log(session.user);
    // nothing gets logged into the terminal?? WTF

    return session;
  },
});



CodePudding user response:

since you are using:

import CredentialsProvider from "next-auth/providers/credentials";

that is next-auth v4. in new version of next-auth this code is not valid anymore:

 session: { jwt: true },

Instead, you should use

session: {
    strategy: "jwt",
  },

Then in jwt callback

//   jwt callback is only called when token is created
async jwt({ token, user }) {
      if (user) {
        token = user;
        // token = user;
        token.user=user
      }
      return Promise.resolve(token);
    },

then in session callback:

session: async ({ session, token }) => {
  // session callback is called whenever a session for that particular user is checked
 // in above function we created token.user=user
  session.user = token.user;
  // you might return this in new version
  return Promise.resolve(session)
},
  • Related