Next Auth Credentials Provider JWT / Session callback
Asked Answered
T

1

11

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;
  },
});



Teador answered 15/4, 2022 at 2:30 Comment(1)
what is the version of next-authRigsdaler
R
7

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)
},
Rigsdaler answered 21/4, 2022 at 1:22 Comment(1)
Is there any way to provide a session saved in the database rather than using JWT that is kept at the session cookie? This can be done using the strategy "database" or "adapter" but it will not work with CredentialsProvider.Americanist

© 2022 - 2024 — McMap. All rights reserved.