From e2872a3d18720223da7cfa857d0d1495a0276994 Mon Sep 17 00:00:00 2001 From: Firman Ramdhani <33869609+firmanramdhani@users.noreply.github.com> Date: Mon, 27 Jul 2026 12:34:48 +0700 Subject: [PATCH] fix: enhance 401 error handling by redirecting to login with current path --- apps/web/src/core/lib/api-client.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/web/src/core/lib/api-client.ts b/apps/web/src/core/lib/api-client.ts index 1eb34bb..6e45437 100644 --- a/apps/web/src/core/lib/api-client.ts +++ b/apps/web/src/core/lib/api-client.ts @@ -40,11 +40,26 @@ export const apiClient = createHttpClient( // ── Error Interceptor ───────────────────────────────────────── onResponseError: async (error) => { - if (error.response?.status === 401) { - // Clear stale token and redirect to login + const status = error.response?.status; + + // Catch 401 (Unauthorized) on request + if (status === 401) { + // Delete invalid tokens 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; }, },