NextJS accessing third party api from client, unable to get a token sometimes

Hi @jon_s,

Welcome to the Auth0 Community!

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:

Hope this helps!
Best regards,
Remus