44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
// api.ts
|
|
import axios from 'axios';
|
|
|
|
const api = axios.create({
|
|
baseURL: import.meta.env.VITE_API_BASE_URL,
|
|
withCredentials: true
|
|
});
|
|
|
|
// Add a request interceptor to add the auth token
|
|
api.interceptors.request.use(
|
|
(config) => {
|
|
const authData = localStorage.getItem('auth_data');
|
|
if (authData) {
|
|
try {
|
|
const { accessToken, tokenType } = JSON.parse(authData);
|
|
if (accessToken) {
|
|
config.headers.Authorization = `${tokenType} ${accessToken}`;
|
|
}
|
|
} catch (error) {
|
|
console.error('Error parsing auth data:', error);
|
|
}
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// Add a response interceptor to handle token expiration
|
|
api.interceptors.response.use(
|
|
(response) => response,
|
|
async (error) => {
|
|
if (error.response?.status === 401) {
|
|
// Clear invalid token
|
|
localStorage.removeItem('auth_data');
|
|
// Redirect to login
|
|
window.location.href = '/login';
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default api;
|