|
1 | 1 | import axios from "axios"; |
2 | 2 |
|
3 | 3 | const api = axios.create({ baseURL: process.env.NEXT_PUBLIC_BACKEND_URL }); |
| 4 | +// const token = localStorage.getItem("access_token"); |
| 5 | +api.interceptors.request.use((config) => { |
| 6 | + if (typeof window !== "undefined") { |
| 7 | + const token = localStorage.getItem("access"); // Matches the key in your Login function |
| 8 | + if (token) { |
| 9 | + config.headers.Authorization = `Bearer ${token}`; |
| 10 | + } |
| 11 | + } |
| 12 | + return config; |
| 13 | +}); |
| 14 | + |
| 15 | +// Response Interceptor: Handle expired tokens |
| 16 | +api.interceptors.response.use( |
| 17 | + (response) => response, |
| 18 | + async (error) => { |
| 19 | + const originalRequest = error.config; |
| 20 | + |
| 21 | + // If error is 401 and we haven't retried yet |
| 22 | + if (error.response?.status === 401 && !originalRequest._retry) { |
| 23 | + originalRequest._retry = true; |
| 24 | + const refreshToken = localStorage.getItem("refresh"); |
| 25 | + |
| 26 | + if (refreshToken) { |
| 27 | + try { |
| 28 | + // Attempt to get a new access token |
| 29 | + const res = await axios.post( |
| 30 | + `${process.env.NEXT_PUBLIC_BACKEND_URL}/token/refresh/`, |
| 31 | + { |
| 32 | + refresh: refreshToken, |
| 33 | + }, |
| 34 | + ); |
| 35 | + |
| 36 | + if (res.status === 200) { |
| 37 | + localStorage.setItem("access", res.data.access); |
| 38 | + // Retry the original request with the new token |
| 39 | + originalRequest.headers.Authorization = `Bearer ${res.data.access}`; |
| 40 | + return api(originalRequest); |
| 41 | + } |
| 42 | + } catch (refreshError) { |
| 43 | + // Refresh token expired too -> Log user out |
| 44 | + localStorage.removeItem("access"); |
| 45 | + localStorage.removeItem("refresh"); |
| 46 | + window.location.href = "/login"; |
| 47 | + console.error("Refresh Error:", refreshError); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + return Promise.reject(error); |
| 52 | + }, |
| 53 | +); |
4 | 54 |
|
5 | 55 | export default api; |
0 commit comments