How to handle session expiry in NextJS

Ready to post? :mag: First, try searching for your answer.
We recently switched from NextAuth to the updated Auth0 library for NextJS - we’re using NextJS 14.x with the App Router.

One thing that’s not clear from the documentation is how we should handle session expiry from the client.

Example

Application requires authentication by default using the withMiddlewareAuthRequired middleware helper.

Configure session expiry as below:

AUTH0_SESSION_ABSOLUTE_DURATION=30 # seconds
AUTH0_SESSION_ROLLING=false

Open web application and log in. Go to a page that makes a client side AJAX request to an API within the same app (protected with middleware) - /api/foobar. Response returned successfully.

Wait for 30 seconds and then hit a refresh button the page that triggers the same client side request. API returns 401 since the session has now expired.

What is the recommended approach for handling this? I thought maybe to use a NextJS error handler (error.ts) but I’ve been unable to get this work.

For information, the reason we went with absolute expiration, non-rolling sessions is because of needing the session to expire before an access token we also obtain for an external API. Perhaps a better approach is to enable rolling sessions and then enable refresh tokens on the external API?

As a follow up question to the above, it would also be good to understand why doing a hard refresh of the browser actually signs the user back in as I couldn’t see in my browser network tab, any redirection back to Auth0.

1 Like

Hi @benfosterdev,

Welcome back to the Auth0 Community and sorry for the late reply.

There is no build-in method in the Auth0 NextJs SDK to handle the expiration of sessions, so the approach of catching an error is the right one in this case.

A very useful example can be checked out from this github thread and in order to make the session persists after the expiry of the user’s session you can Configure Silent Authentication.

You can fully check out this Knowledge Article which explains the premises of this particular issue.

I hope this helped.
Thanks,
Remus

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