Spaces:
Running
Running
File size: 1,202 Bytes
308a91d 2d5877c 308a91d 7607c2e 2d5877c 308a91d 2d5877c 308a91d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import axios from 'axios';
import toast from 'react-hot-toast';
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL || '',
headers: { 'Content-Type': 'application/json' },
timeout: 15000,
});
// Auto-attach JWT token
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Handle 401 (expired/invalid token)
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401 && !window.location.pathname.startsWith('/login')) {
const code = error.response?.data?.code;
localStorage.removeItem('token');
localStorage.removeItem('user');
if (code === 'SESSION_EXPIRED') {
// Kasir diambil alih perangkat lain
toast.error('⚠️ Sesi Anda diambil alih perangkat lain. Silakan login ulang.', {
duration: 5000,
id: 'session-expired',
});
setTimeout(() => { window.location.href = '/login'; }, 1500);
} else {
window.location.href = '/login';
}
}
return Promise.reject(error);
}
);
export default api;
|