Currently, I am working on an application using Next.js and implementing authentication with NextAuth. However, I am encountering an issue with the getToken function not working properly on the server-side.
I have double-checked my callbacks configuration:
callbacks:{
async jwt({ token, user }) {
return { ...token, ...user }
}
}
I have also attempted to pass the NextAuth secret as an argument in this way:
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET
})
console.log(token)
Every time I call getToken, it returns null, which has prompted me to create a test endpoint to investigate further:
import { getToken } from 'next-auth/jwt'
export default async function handler(req, res) {
const token = await getToken({ req })
res.status(200).json({ user: token })
}
Additionally, I have created a page for testing purposes:
const test = props => {
const { token } = props
return (
<div>
<button onClick={() => console.log(token)}>teste</button>
</div>
)
}
export async function getServerSideProps(context) {
const tokenRes = await fetch(`${process.env.NEXT_PUBLIC_BASE_PATH}/api/test`)
const token = await tokenRes.json()
console.log(token)
return {
props: {
token: token
}
}
}
export default test
The object passed to pageProps shows a null token.
Strangely, when I access the endpoint directly in the browser, I receive the expected token: my token '-'.
I am determined to use getToken effectively on the server-side and middleware to retrieve my token. What could be causing this unexpected behavior? Any guidance or advice would be greatly appreciated!
Thank you in advance for your help!