Search code examples
javascriptnext.jsjwtaclnext-auth

Next-auth getToken dont working on serverside


I'm building an application with Next.js and using NextAuth for authentication. But now I need to use the getToken function, but it doesn't work on the server-side!

I think I configured the callbacks correctly:

callbacks:{
    async jwt({ token, user }) {
      return { ...token, ...user }
    }
}

and I tried passing the NextAuth secret as an argument like this:

const token = await getToken({
      req: request,
      secret: process.env.NEXTAUTH_SECRET
    })

    console.log(token)

but every time I called getToken, it returns null. Now I'm seeing an unexpected behavior, so I created this endpoint for testing:

import { getToken } from 'next-auth/jwt'

export default async function handler(req, res) {
  const token = await getToken({ req })

  res.status(200).json({ user: token })
}

and a page for the same purpose:

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 is: null token

But when I open the endpoint in the browser, I have the expected token: my token '-'

I need to use getToken on the server-side and middleware, and I want to get my token. XD

What is happening? I don't know the best way to proceed.

Thanks in advance!


Solution

  • To whom it may concern,

    This problem occurs when I fetch data using my endpoints like fetch(url). When fetch is called by getServerSideProps, the cookie is not passed automatically.

    To solve this issue, it is necessary to manually pass the cookie as follows:

    export async function getServerSideProps(context) {
      const { req } = context
    
      const tokenRes = await fetch(`${process.env.NEXT_PUBLIC_BASE_PATH}/api/test`, {
        headers: {
          Cookie: req.headers.cookie
        }
      })
    
      const token = await tokenRes.json()
    
      console.log(token)
    
      return {
        props: {
          token: token
        }
      }
    }
    

    This way, getToken works well.