31 lines
978 B
TypeScript
31 lines
978 B
TypeScript
import axios from 'axios';
|
|
|
|
// Centralized axios instance that mirrors apiFetch's behavior: it injects the
|
|
// auth token from localStorage into every outbound request and dispatches an
|
|
// `auth:logout` window event on 401 responses (so AuthContext clears state).
|
|
//
|
|
// Drop-in for the default `axios` export: use `apiClient.get(...)` etc. in
|
|
// place of `axios.get(...)`. The interceptors handle the auth plumbing.
|
|
|
|
export const apiClient = axios.create();
|
|
|
|
apiClient.interceptors.request.use((config) => {
|
|
const token = localStorage.getItem('token');
|
|
if (token && !config.headers.has('Authorization')) {
|
|
config.headers.set('Authorization', `Bearer ${token}`);
|
|
}
|
|
return config;
|
|
});
|
|
|
|
apiClient.interceptors.response.use(
|
|
(response) => response,
|
|
(error) => {
|
|
if (error?.response?.status === 401 && localStorage.getItem('token')) {
|
|
window.dispatchEvent(new Event('auth:logout'));
|
|
}
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
|
|
export default apiClient;
|