Spaces:
Running
Running
| 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; | |