Auth0 Login Session on My Website Randomly Expires While the User Is Still Actively Using the Site

Hi @joeroot.pk80

You are experiencing intermittent, unpredictable session invalidation where logged-in users are unexpectedly treated as unauthenticated during active browsing, even though the initial login works correctly and no explicit logout occurs.

**This is typically caused by one of three issues:

  1. The application failing to renew access tokens before they expire.
  2. Refresh token rotation not being properly handled or stored.
  3. Browser security settings or third-party cookie policies blocking silent authentication. The solution requires systematic diagnosis of your token lifecycle, refresh token configuration, and silent authentication flow.**

[ROOT CAUSE]
Auth0 access tokens have a short lifetime (typically 1 hour) and must be renewed before expiration. If your application does not proactively refresh the token using a refresh token or silent authentication, the user will be treated as unauthenticated once the access token expires. Additionally, if refresh token rotation is enabled, the old refresh token becomes invalid after each exchange, and your application must capture and store the new one. Finally, browser security features (Total Cookie Protection in Firefox, Brave Shields, third-party cookie blocking) can prevent silent authentication from working, causing token renewal to fail silently.

You are experiencing intermittent, unpredictable session invalidation where logged-in users are unexpectedly treated as unauthenticated during active browsing, even though the initial login works correctly and no explicit logout occurs.

Official Solution:

Step 1: Verify your token configuration in Auth0 Dashboard

  1. Navigate to Auth0 Dashboard → Applications → Your Application → Settings → Advanced → Token Endpoint Authentication Method.
  2. Check the token lifetime settings — Go to Settings → Token Configuration and note:
    • ID Token Expiration: typically 36000 seconds (10 hours)
    • Access Token Expiration: typically 86400 seconds (24 hours) for APIs, but often 3600 seconds (1 hour) for SPAs
    • Refresh Token Rotation: Check if enabled under Refresh Token Behavior
  3. If Refresh Token Rotation is enabled, verify that your application captures and stores the new refresh token returned in each token exchange response. The old refresh token is immediately invalidated.

Step 2: Verify your application's token renewal mechanism

  1. Check if you are using getAccessTokenSilently() or equivalent — This method should be called before making authenticated requests. If your application only calls this method once at login and never again, tokens will expire and the user will be logged out.
  2. Implement proactive token refresh — Add a mechanism to refresh tokens before they expire. Example for auth0-react:
    import { useAuth0 } from "@auth0/auth0-react";
    import { useEffect } from "react";
    

    export function TokenRefreshManager() {
    const { getAccessTokenSilently, isAuthenticated } = useAuth0();

    useEffect(() => {
    if (!isAuthenticated) return;

    const interval = setInterval(async () => {
      try {
        await getAccessTokenSilently();
        console.log("Token refreshed successfully");
      } catch (error) {
        console.error("Token refresh failed:", error);
      }
    }, 50 * 60 * 1000);
    
    return () => clearInterval(interval);
    

    }, [isAuthenticated, getAccessTokenSilently]);
    return null;

    }

  3. Ensure refresh tokens are enabled — In your Auth0 SDK initialization, verify that useRefreshTokens: true is set (for auth0-react) or equivalent for your SDK.

Step 3: Check browser security and third-party cookie settings

  1. Test in different browsers — Try Chrome, Firefox (with Total Cookie Protection disabled), and Safari. If the issue only occurs in one browser, it is likely a browser security setting.
  2. Check Firefox Total Cookie Protection — If using Firefox, disable Total Cookie Protection for your domain and test. This feature can block silent authentication.
  3. Check browser third-party cookie settings — Ensure third-party cookies are allowed for your Auth0 domain, as silent authentication relies on them.
  4. Test in incognito/private mode — If the issue does not occur in private mode, it may be related to cached data or browser extensions.

Step 4: Enable detailed logging to capture the exact failure point

  1. Add logging to your token refresh calls:
    const handleTokenRefresh = async () => {
      const timestamp = new Date().toISOString();
      try {
        const token = await getAccessTokenSilently();
        console.log(`[${timestamp}] Token refresh succeeded. Expires at: ${new Date(Date.now() + 3600000).toISOString()}`);
      } catch (error) {
        console.error(`[${timestamp}] Token refresh failed:`, error.error, error.error_description);
      }
    };
  2. Log when the user is treated as unauthenticated:
    useEffect(() => {
      const timestamp = new Date().toISOString();
      console.log(`[${timestamp}] isAuthenticated changed to: ${isAuthenticated}`);
    }, [isAuthenticated]);
  3. Check Auth0 tenant logs — Go to Auth0 Dashboard → Logs and filter for your user. Look for:
    • s (Success Login) events
    • ss (Success Silent Auth) events
    • f (Failed Login) events
    • fs (Failed Silent Auth) events
    • fce (Failed Cross-Origin Exchange) events

Step 5: Check for refresh token rotation issues

  1. If Refresh Token Rotation is enabled, verify that your application stores the new refresh token returned in the response. Example:
    // After token exchange, the response includes a new refresh_token
    const response = await fetch('https://YOUR_DOMAIN/oauth/token', {
      method: 'POST',
      body: JSON.stringify({
        grant_type: 'refresh_token',
        refresh_token: storedRefreshToken,
        client_id: YOUR_CLIENT_ID,
        client_secret: YOUR_CLIENT_SECRET,
      }),
    });
    

    const data = await response.json();
    // IMPORTANT: Store the new refresh token
    localStorage.setItem(‘refresh_token’, data.refresh_token);

  2. If using an SDK, verify that the SDK is configured to handle rotation automatically. Most modern SDKs (auth0-react, auth0-spa-js v2+) handle this automatically.

Step 6: Review your application's session storage strategy

  1. Verify that tokens are stored in the correct location — Use cacheLocation: 'localstorage' or cacheLocation: 'memory' depending on your security requirements. Memory-only storage will lose tokens on page refresh.
  2. Ensure session data is not being cleared unexpectedly — Check if any code is calling logout(), clearing localStorage, or resetting the authentication context.

Why increasing token lifetime alone is not the solution:

Increasing token lifetime delays the problem but does not fix the underlying issue. If your application is not renewing tokens, a longer-lived token will eventually expire, and the user will still be logged out. Additionally, longer-lived tokens pose a security risk if compromised.

Recommended next steps:

  1. Implement the token refresh logging above and capture logs from affected user sessions.
  2. Check Auth0 tenant logs for failed silent authentication (fs events) or failed cross-origin exchange (fce events) during the time the user reports being logged out.
  3. Test in multiple browsers to isolate whether the issue is browser-specific.
  4. If you are using refresh token rotation, verify that your application is storing the new refresh token on each exchange.
  5. Contact Auth0 Support with your tenant ID, application ID, and the logs from Step 2 if the issue persists after these checks.

Please follow the diagnostic steps above and gather the logs before contacting Auth0 Support, as this will help them identify the exact cause of your intermittent session invalidation.

I would highly recommend to dig into this issue further by reading this community topic on Access Tokens Refreshing After User Session Timeout and Silent Authentication Not Refreshing Tokens Properly.

Let me know if the information above is useful for the issue that you are experiencing. I will be looking forward to your updates on the matter.

Kind Regards,
Nik