0

I am trying to learn next-auth, I finally got the login to work but when I pass the id from the user in the database it doesn't show up in the session only the values that I provided null to show up

import NextAuth from 'next-auth'
import CredentialProvider from 'next-auth/providers/credentials'
import connectMongo from '../../../lib/db'
import User from '../../../models/userModel'

export const authOptions = {
  session: {
    strategy: 'jwt',
  },
  providers: [
    CredentialProvider({
      async authorize(credentials) {
        await connectMongo()
        const u = await User.findOne({ username: credentials.username })
        console.log(u.id)
        if (u) {
          return {
            id: u.id,
            name: null,
            email: null,
            image: null,
          }
        }

        // login failed
        return null
      },
    }),
  ],
}

export default NextAuth(authOptions)

login is successful with no errors but the id doesn't show up in the props. {email: null, image: null, name: null} is all that is returned. If I don't add null to all those keys it returns this error SerializableError: Error serializing .session.user.name returned from getServerSideProps in "/authenticated". Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

import { authOptions } from './api/auth/[...nextauth]'
import { unstable_getServerSession } from 'next-auth/next'

function Authenticated(props) {
  return <div>Authenticated</div>
}
export default Authenticated

export async function getServerSideProps(context) {
  const session = await unstable_getServerSession(
    context.req,
    context.res,
    authOptions
  )

  if (!session) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }

  return {
    props: {
      session,
    },
  }
}

get session in getServerSideProps also returns an empty object after successful login with no errors

import { getSession } from 'next-auth/react'

function Authenticated(props) {
  console.log(props)
  return <div>Authenticated</div>
}
export default Authenticated

export async function getServerSideProps(context) {
  const session = await getSession({ req: context.req })

  if (!session) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }

  return {
    props: { session },
  }
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
bobby_turks
  • 75
  • 1
  • 6

1 Answers1

0

One solution is to add a callbacks property to the NextAuth configuration/settings object that is passed in.

Here's an example of adding the callbacks property to find and pass additional information to the session.

export default NextAuth({
  session: {
    jwt: true,
  },
  callbacks: {
    session: async (session) => {
      if (!session) return;
      const client = await connectToDatabase();
      const usersCollection = client.db().collection('users');
      const userData = await usersCollection.findOne({
        email: session.user.email,
      });

      return {
        session: {
          user: {
            id: userData._id,
            email: userData.email
          },
          extra: {
            test: "It worked!"
          }
        }
      };
    },
  },
  providers: [
    Providers.Credentials({
      async authorize(credentials) {
        const client = await connectToDatabase();
        const usersCollection = client.db().collection('users');
        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) {
          client.close();
          throw new Error('Could not log you in!');
        }

        client.close();
        return { email: user.email };

      },
    }),
  ],
});

By the way, the answer is also answered at this link from a similar question: How do I add data to the client API in next-auth?

Sheldon
  • 1
  • 1