Hi there. We have a dashboard that is protected in NextJS (we check for a valid session in layout.tsx and redirect to login if there isn’t one). Often see in our error logs that people experience 401s when we try to get an access token for them to access our third party api, or if we try to access the profile using useUser.
My question is, why would this happen, and what should we do? Is this because a token expires during their session or something like that?
If we get a 401 from an auth0 hook or cannot get an access token, should that person still be considered logged in, or should we log them out? Clearly the request they are about to make would fail correct?
There seems to be very little in the docs about this, it shows this example, but provides no guidance on the meaning of getting an error here
async function fetchData() {
try {
const token = await getAccessToken();
// call external API with token...
} catch (err) {
// err will be an instance of AccessTokenError if an access token could not be obtained
The most common case in which a user received a 401 Unauthorized error is because the Access Token has expired, so that is why the getAccessToken() function returns this 401 error. You should handle the error by logging the user out and redirect them to the login page.
An example of what you could use in the catch block in order to handle the error would be:
if (error.status === 401) {
// Redirect to a specific route that logs the user out
// or call handleLogout directly
console.error('Session expired or invalid. Logging out.');
await handleLogout(req, res);
// You might also redirect them here
res.redirect('/api/auth/login');
}
I would also recommend enabling Refresh Tokens in order to automatically renew the access token, so you can also check this articles:
Thanks for the response, however I am not entirely sure that this is the right path. The reason is that in many of these cases, it seems as though the application “recovers”, and it able to fetch a valid token subsequently. I have seen this many times, where it fails, and then succeeds seconds or minutes later to get a valid token. Is this not possible?
Hi, I have some more info. It seems in many cases, we are actually receiving a 502 error from the /auth/access-token endpoint. I think that this might be during deployments. Is this expected?