Next.js Discord

Discord Forum

User object is empty in JWT, using the Credentials provider in Next-Auth

Unanswered
Poitevin posted this in #help-forum
Open in Discord
Avatar
PoitevinOP
Package versions:
"next": "^14.0.1",
"next-auth": "^5.0.0-beta.4",


I am following some examples on how to implement the credentials provider with Next.js 14 and Next-Auth v5, but having a problem with my session token. I am returning a user object from my authorize() method, but after trying to get the returned data in the session via auth() method, the user object is empty {}.

Here's my code:

// ./auth.ts
export const { auth, signIn, signOut } = NextAuth({
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      return !!auth?.user;
    },
  },
  providers: [
    Credentials({
      async authorize(credentials) {
        const parsedCredentials = z
          .object({ email: z.string().email(), password: z.string().min(6) })
          .safeParse(credentials);

        if (parsedCredentials.success) {
          const { email, password } = parsedCredentials.data;
          // call to database, returning { id, password, profiles: [{ id }]}
          const user = await getUser(email);
          if (!user) return null;

          const passwordsMatch = await bcrypt.compare(password, user.password);

          if (passwordsMatch) {
            // here i return the object i want to have in my session
            return {
              id: user.id,
              profileId: user.profiles[0].id,
            };
          }
        }

        return null;
      },
    }),
  ],
} satisfies NextAuthConfig);


And then in a server action, I try:

async function createPost() {
  const { user } = await auth();
  console.log(user); // {} instead of { id: ..., profileId: ... }
}


What am I doing wrong? 🤔

0 Replies