fix: enhance 401 error handling by redirecting to login with current path
This commit is contained in:
@@ -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;
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user