After successfully implementing next-auth for login, I encountered an issue where the user id from the database was not showing up in the session. Only the values that I provided as null were displaying.
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)
Although the login process was successful without any errors, only {email: null, image: null, name: null} were returned and the user id was missing from the props. When I tried to omit null values, it resulted in a 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,
},
}
}
Upon checking the session in getServerSideProps after a successful login, it returns an empty object 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 },
}
}