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