In Next.js auth0.getAccessToken behaves differently in pages router and app router

Hello,

I have two versions of the same endpoint one for the PagesRouter (I am currently using in the app) and one for the AppRouter. The endpoint contains only auth0.getAccessToken with refresh: true.

I have Test component where the endpoints are called.

When calling the AppRouter version (/api/app-refresh) it works as expected:

  1. Call /api/app-refresh
  2. The response contains in body expires_at and in the header there are set-cookie (__session__0=ABCD, __session__1=XYZ, __session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT, appSession=; Path=/; Max-Age=0)
  3. Then when calling the endpoint /auth/access-token. The request has headers __session__0=ABCD, __session__1=XYZ and the response contains the same expires_at value and also the token it self is same as the one loged in the endpoint
  4. I can repeat the process indefinitely and it works

But when calling the PagesRouter version (/api/pages-refresh):

  1. Call /api/pages-refresh
  2. The response contains in body expires_at but in the header there is only set-cookie appSession=; Path=/; Max-Age=0
  3. Then when calling the endpoint /auth/access-token the returned token does not match with the loged one in the endpoint and has different expires at
  4. When called again I get error “The access token has expired and there was an error while trying to refresh it.”

Code available in the forked repo at github: radimkafka/auth0-nextjs-samples/tree/getAccessToken

According to the exmaples page I think it should work the same. Am I doing something wrong, does it work as expected or is it a bug that should be fixed?

Hi @radim-kafka

I am sorry about the delayed response to your inquiry regarding the Next.js routes.

From what I understand regarding the implementation you are talking about and the SDK behaviour, it appears that when calling both the app and page routers, instead of appending the headers it is overwriting them causing the aforementioned issue.

I believe you should be able to use only the App Router since both of them share the same session configuration and the cookies set by it should be visible and valid for any of your Page Router pages. As a possible workaround if you must use Page Routers for your application would be to manually retrieve the session and appending headers as such:

// app/api/refresh-token/route.ts
import { getAccessToken } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';

export async function GET() {

  const { accessToken, expiresAt } = await getAccessToken({ refresh: true });
  
  return NextResponse.json({ 
    accessToken, 
    expiresAt 
  });
}

Otherwise, as you have mentioned, this appears to be a bug which has been reported on the SDKs Github Page and you can check it out here.

If you have any other questions, let me know!

Kind Regards,
Nik