fix: enhance 401 error handling by redirecting to login with current path

This commit is contained in:
Firman Ramdhani
2026-07-27 12:34:48 +07:00
parent 0f9b44e70f
commit e2872a3d18
+18 -3
View File
@@ -40,11 +40,26 @@ export const apiClient = createHttpClient(
// ── Error Interceptor ───────────────────────────────────────── // ── Error Interceptor ─────────────────────────────────────────
onResponseError: async (error) => { onResponseError: async (error) => {
if (error.response?.status === 401) { const status = error.response?.status;
// Clear stale token and redirect to login
// Catch 401 (Unauthorized) on request
if (status === 401) {
// Delete invalid tokens
await appStorage.removeItem(AppStorageKey.ACCESS_TOKEN); await appStorage.removeItem(AppStorageKey.ACCESS_TOKEN);
window.location.href = '/auth/login';
// Retrieve the current path and query string (example: /dashboard/settings?tab=profile)
const currentPath = window.location.pathname + window.location.search;
// Retrieve the current path and query string (example: /dashboard/settings?tab=profile)
const redirectParam = encodeURIComponent(currentPath);
// Use replace() instead of href.
// replace() will not save the history of the page with this error,
// so that if the user presses the 'back' button in the browser from the login page,
// they won't get stuck in an infinite loop back to the login page.
window.location.replace(`/auth/login?redirect=${redirectParam}`);
} }
throw error; throw error;
}, },
}, },