From 9ba67a94f90d0620dbcbf9c99021c725a8453667 Mon Sep 17 00:00:00 2001 From: Dovy Mus Date: Thu, 19 Mar 2026 20:46:48 +0100 Subject: [PATCH] fix(auth): logout user on delete or jwt expire --- apps/frontend/src/lib/api.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/apps/frontend/src/lib/api.ts b/apps/frontend/src/lib/api.ts index 7558c5fb..241ee997 100644 --- a/apps/frontend/src/lib/api.ts +++ b/apps/frontend/src/lib/api.ts @@ -1,11 +1,9 @@ import axios from 'axios'; import { useAuthStore } from '@/store/authStore'; +import { useCurrentUserStore } from '@/store/currentUserStore'; + +const AUTH_401_TRIGGERS = /^\/(auth\/me|users\/me|users\/me\/)/; -/** - * The global Axios instance for making HTTP requests. - * * Pre-configured with the backend base URL and standard headers. - * Use this instance instead of `axios` directly to ensure consistent behavior. - */ const api = axios.create({ baseURL: '/api', headers: { @@ -14,20 +12,22 @@ const api = axios.create({ timeout: 5000, }); -// Request interceptor → attach token api.interceptors.request.use((config) => { const token = useAuthStore.getState().token; if (token) config.headers.Authorization = `Bearer ${token}`; return config; }); -// Response Interceptor api.interceptors.response.use( (response) => response, (error: unknown) => { if (axios.isAxiosError(error)) { if (error.response?.status === 401) { - console.warn('Unauthorized! Redirecting to login...'); + const url = error.config?.url ?? ''; + if (AUTH_401_TRIGGERS.test(url)) { + useAuthStore.getState().clearAuthenticated(); + useCurrentUserStore.getState().clearUser(); + } } return Promise.reject(error); }