Files
khata-ui/react-auth/axios.ts
Vishesh 'ironeagle' Bangotra 4cabe0be0c fix: replace nested Routes with useLocation, remove pushState+reload, add debug logs
- ProfileRoutes: removed nested <Routes> in favor of useLocation()/useNavigate()
  with strict allowlist for /profile/me and /profile/me/edit
- ProfileComponentWrapper: replaced pushState()+reload() with navigate()
- useApi: log 401 and non-401 errors
- contexts.tsx: log fetchCurrentUser lifecycle and auth:unauthorized events
- axios.ts: log auth server 401s
2026-07-19 18:12:48 +05:30

41 lines
1.0 KiB
TypeScript

import axios, { AxiosInstance } from "axios";
import { tokenStore } from "./token";
export function attachAuthInterceptors(client: AxiosInstance) {
client.interceptors.request.use((config) => {
const token = tokenStore.get();
if (token) {
if (!config.headers) {
(config as any).headers = {};
}
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
client.interceptors.response.use(
(res) => res,
(error) => {
if (error.response?.status === 401) {
console.log("[authAxios] 401 from %s %s", error.config?.method, error.config?.url);
tokenStore.clear();
window.dispatchEvent(new CustomEvent("auth:unauthorized"));
}
return Promise.reject(error);
}
);
}
/**
* Factory for app APIs that need auth
*/
export function createApiClient(baseURL: string): AxiosInstance {
const client = axios.create({
baseURL,
headers: { "Content-Type": "application/json" },
});
attachAuthInterceptors(client);
return client;
}