NextAuth session returns jwt with no user data

Viewed 33

I am using next auth to authenticate users through credentials stored in a database. A JWT is returned and should contain common data such as their first and last name.

My […nextauth].ts file is as follows:

import Credentials from 'next-auth/providers/credentials';

import { verifyPassword } from '../../../lib/auth';
import { connectToDatabase } from '../../../lib/db';

export default NextAuth({
  session: {
    strategy: 'jwt',
  },
  providers: [
    Credentials({
      async authorize(credentials: Record<string, string> | undefined) {
        if (credentials == undefined) {
          throw new Error('Credentials not defined.');
        }
        const client = await connectToDatabase();

        const usersCollection = client
          .db(process.env.DB_DB)
          .collection('account');

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

        if (!user) {
          client.close();
          throw new Error('No user found.');
        }

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

        if (!isValid) {
          throw new Error('Your password is incorrect.');
        }
        client.close();

        return {
          user: {
            email: user.email,
            firstName: user.firstName,
            lastName: user.lastName,
          },
        };
      },
      credentials: {},
    }),
  ],
  pages: {
    signIn: '/',
  },
});

The session I receive from getSession is

expires: "2022-10-05T18:57:13.557Z"
user:
[[Prototype]]: Object
[[Prototype]]: Object

The authentication works as intended, throwing errors where credentials don’t match and returning the JWT where the details are correct.

I have made sure the user is being returned from the database and is being stored in the user variable. It just doesn’t seem to return anything inside.

1 Answers

You have to return Promise

 const returnedUser={
            email: user.email,
            firstName: user.firstName,
            lastName: user.lastName,
          },

 return Promise.resolve(returnedUser);
Related