Skip to content

Bug: Users with expired/invalid JWT see app UI with raw error alert instead of being redirected to login #11

@xinpehr

Description

@xinpehr

Description

When a user's JWT token expires or is cleared (e.g. browser clears storage, session timeout), they can still see the app UI (e.g. /app/chat). API calls fail with 401 and the raw error message "You are not authorized to access this resource" is shown as a toast notification at the bottom of the screen — but the user remains on the page with no way to interact.

Expected behavior: User should be automatically logged out and redirected to the login page.

Actual behavior: User sees the full app UI with a red error toast. The page is non-functional.

Root Cause

The Api class in resources/assets/js/api.js has no handling for 401 responses. When the backend returns a 401 JSON response for API routes (/api/*), the frontend just displays the error message via toast.error() and throws an ApiError — it never clears the session or redirects.

Relevant code (api.jsrequest() method):

// Current behavior: shows toast and throws, user stays on page
if (this.config.toast && message) {
    toast.error(message);
    window.modal.close();
}
throw new ApiError(response, message || response.statusText);

Suggested Fix

Add a 401 handler in the Api.request() method before the generic error handling. When a 401 is received (excluding /auth/ routes to avoid breaking the login/OTP flow), clear the JWT and redirect to login:

if (response.status === 401 && !url.pathname.includes('/auth/')) {
    localStorage.removeItem('jwt');
    document.cookie = 'user=; Max-Age=0; path=/;';
    window.location.href = '/login';
    return new Promise(() => {});
}

Note: The OTP auth flow (login.js) uses direct fetch() calls, not the Api class, so this change does not affect authentication. The /auth/ exclusion covers auth/auth.js which uses Api with base /api/auth.

Steps to Reproduce

  1. Log in to the app normally
  2. Open browser DevTools → Application → Local Storage
  3. Delete the jwt key (or clear cookies)
  4. Interact with the app (send a chat message, navigate, etc.)
  5. Observe the red toast error instead of redirect to login

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions