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

**URL:** <https://community.auth0.com/t/next-js-using-getsession-or-getaccesstoken-resulting-in-user-authentication-being-lost/139237>\
**Category:** Get Help\
**Tags:** authentication-sessions, sessions\
**Created:** [July 18, 2024, 1:52pm UTC](https://community.auth0.com/t/next-js-using-getsession-or-getaccesstoken-resulting-in-user-authentication-being-lost/139237 "2024-07-18T13:52:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kat1](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/User_font_awesome.svg/768px-User_font_awesome.svg.png) [@kat1](https://community.auth0.com/u/kat1)\
**Post date:** [July 18, 2024, 1:52pm UTC](https://community.auth0.com/t/next-js-using-getsession-or-getaccesstoken-resulting-in-user-authentication-being-lost/139237/1 "2024-07-18T13:52:04Z")

</div>

Ready to post? 🔍 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.

```auto
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.

```auto
        <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.

```auto
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'

```

---

<div class="post-metadata">

**Author:** ![remus.ivan](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/remus.ivan/32/68771_2.png) [@remus.ivan](https://community.auth0.com/u/remus.ivan)\
**Post date:** [February 7, 2025, 6:50pm UTC](https://community.auth0.com/t/next-js-using-getsession-or-getaccesstoken-resulting-in-user-authentication-being-lost/139237/3 "2025-02-07T18:50:59Z")

</div>

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](https://auth0.com/docs/get-started/apis/api-settings#access-settings).
- Make sure the “Refresh Token” grant is enabled in the [Application Settings](https://auth0.com/docs/get-started/applications/application-settings#grant-types) (this is the default).

This information is outlined in one of our [Knowledge Articles](https://community.auth0.com/t/token-refresh-with-nextjs-auth0-sdk/107142) as well.

You can also check this github repository for examples of this implementation [here](https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#protect-an-api-route).

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

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [February 21, 2025, 6:51pm UTC](https://community.auth0.com/t/next-js-using-getsession-or-getaccesstoken-resulting-in-user-authentication-being-lost/139237/4 "2025-02-21T18:51:33Z")

</div>

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