Skip to content

fix: handle 401 responses globally with axios interceptor (Closes #473) - #593

Open
waterWang wants to merge 1 commit into
Protocol-Guild:mainfrom
waterWang:fix/473-axios-401-interceptor
Open

fix: handle 401 responses globally with axios interceptor (Closes #473)#593
waterWang wants to merge 1 commit into
Protocol-Guild:mainfrom
waterWang:fix/473-axios-401-interceptor

Conversation

@waterWang

Copy link
Copy Markdown

Summary

Adds a global axios response interceptor that handles 401 Unauthorized responses across the entire application. Previously, expired tokens caused silent failures (spinners, empty tables) with no feedback to the user.

Changes

  • frontend/src/utils/api.ts — Added handleUnauthorized function that:

    • Catches every 401 response from both the shared api instance and bare axios.* calls
    • Clears the expired token from localStorage
    • Shows a sonner toast: "Session expired, please log in again"
    • Redirects to /login so the user can re-authenticate
    • Skips /auth/ endpoints to avoid interfering with legitimate login flows
    • Guards against infinite redirect loops when already on the login page
  • frontend/src/main.tsx — Added side-effect import of ./utils/api to ensure the global interceptor is registered at app startup

Why this approach

The project's service files use bare axios.get/post calls (not a shared instance). Registering the interceptor on both axios.interceptors.response (global) and api.interceptors.response (shared instance) ensures every API call is covered — no silent failures slip through.

Testing

  • TypeScript compiles clean (tsc --noEmit passes)
  • 401 on /auth/ endpoints is skipped (login flow unaffected)
  • 401 on non-auth endpoints clears token + shows toast + redirects to /login
  • Already on /login when 401 fires → no redirect loop

Closes #473

Add a global axios response interceptor so expired sessions never surface as
silent spinners or empty tables. On 401 (non-auth endpoints) the interceptor:
clears the payd_auth_token from localStorage, shows a sonner toast
'Session expired, please log in again', and redirects to /login.

Registers on both the shared api instance and bare axios calls, with guards
for /auth endpoints and redirect loops. Closes Protocol-Guild#473
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Handle 401 responses globally with axios interceptor

1 participant