Search code examples
javascriptnext.jsnext-auth

Is secret needed in getToken method of NextAuth?


In my API endpoint, it needed the user's session to verify if the user is authorized to make this request. In order to do so, I use

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

This is the formal and correct way. However, it also works perfectly fine if I do this without the secret:

const session = await getToken({ req })

If I don't explicitly pass the secret into the getToken method, does it automatically get it from the NextAuth object from [...nextauth].js?


Solution

  • You're only required to pass the secret to the getToken call if you have not set the NEXTAUTH_SECRET environment variable.

    The getToken() helper requires the following options:

    • req - (object) Request object
    • secret - (string) JWT Secret. Use NEXTAUTH_SECRET instead.

    NextAuth.js, Configuration Options, JWT Helper

    In your case, since you have set NEXTAUTH_SECRET you do not need to pass secret to getToken.