Next.js using getSession or getAccessToken resulting in user authentication being lost

Ready to post? :mag: First, try searching for your answer.
I am writing to get assistance with handling authentication in Next.js. I am using a middleware to set Authorization access token please see snippet below.

export default withMiddlewareAuthRequired(async function middleware(req: NextRequest) {
    if (req.nextUrl.pathname.startsWith('/api/auth')) {
        return;
    }

    const response = NextResponse.next({
        request: {
            headers: new Headers(req.headers),
        },
    });

    const user = await getSession(req, response);
    const token = user?.accessToken;

    response.headers.set('Authorization', `Bearer ${token}`);

    return response;
});

export const config = {
    matcher: ['/api/:path*'],
};

What I have noticed is whenever a protected route is triggered and as a result, with getSession() or getAccessToken() functions from @auth0/nextjs-auth0/edge executed, my session is lost. With this, when I try to access another protected route, I will unauthorized. Refreshing the app at this point, I am unauthorized and the only way to continue is to login again.

How can I avoid this from happening, as using getSession() or getAccessToken() is a crucial part of my app?

For more context, in my layout.tsx I am using UserProvider to wrap the whole app.

        <html lang="en">
            <body className={`${inter.className}`}>
                <UserProvider>
        		<Navigation />
                        {children}
                </UserProvider>
            </body>
        </html>

My .env.local I have tripled checked and all values are correct, I can login or register successfully.

AUTH0_SECRET='long-secret'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='base-domain-here'
AUTH0_CLIENT_ID='id-here'
AUTH0_CLIENT_SECRET='secret-here'
AUTH0_AUDIENCE='audience-here'
AUTH0_SCOPE='openid profile'

Hi @kat1

Welcome to the Auth0 Community

From what i have checked there doesn’t seem to be a particular issue with your code. However as mentioned in the NextJs SDK as well :

// getAccessToken will fetch you a new one using the refresh_token grant

So the possible solution for using both getSession() or getAccessToken() in a server-side environment would be to :

  • Include the offline_access scope in the configuration (or AUTH0_SCOPE).
  • Check “Allow Offline Access” in the API Settings.
  • Make sure the “Refresh Token” grant is enabled in the Application Settings (this is the default).

This information is outlined in one of our Knowledge Articles as well.

You can also check this github repository for examples of this implementation here.

You can let us know if this did the trick for you and I hope this helped,
Remus

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.