The access token expired and a refresh token is not available. The user will need to sign in again. What now?

Hey fellow devs,

I got Auth0 going to log my users in and out. However I am currently testing on what happens when the access token expires. Currently I only get this error:

I am using nextjs-auth0 ^1.9.1 (with a NestJS API) like so on the page that spits out that error:

export const getServerSideProps = withPageAuthRequired({
  async getServerSideProps(context) {
    const { accessToken } = await getAccessToken(context.req, context.res)
    return {
      props: { accessToken },
    }
  },
})

My api catch all route looks like this:

import { handleAuth } from "@auth0/nextjs-auth0"
export default handleAuth()

and the .env like this:

AUTH0_SECRET='blablabla'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://blablabla.eu.auth0.com'
AUTH0_CLIENT_ID='blablablablablabla'
AUTH0_CLIENT_SECRET='blablablablablabla'
AUTH0_AUDIENCE='blabla-nestjs-api'

What now? Should I redirect to login in getServersideProps()? Should I enable refresh tokens, if so, how? Anyone got any guidance? Would gladly appreciate any help. I got to admit, the documentation on that topic is extremely sparse and has lots of potential for improvement.

Only thing I found was this useUser and getAccessToken not synced · Issue #452 · auth0/nextjs-auth0 · GitHub and that sadly doesn’t help at all. Do I need to enable offline_access scope to make the refresh tokens work? Already tried that, then I get

I am heavily confused by all this. Please think about writing a simple guide for this.

1 Like

Hi @amg1,
I can’t help with the specific next.js issue, but I suggest you ensure refresh token support is enabled before using the offline_access scope.

Please, go to your NestJS API in the Auth0 dashboard and enable refresh token support through the Allow Offline Access toggle button

Save the API settings.

Now, in your app, you can use the offline_access scope to get a refresh token along with the ID and access token.

References:

I also suggest enabling refresh token rotation to improve security (Auth0 dashboard → your App → Refresh Token Rotation section).
Check out this article to learn more about refresh tokens.

I hope this may help.

To set the scope, simply define AUTH0_SCOPE in your .env

AUTH0_SCOPE='openid profile email offline_access'