|
| 1 | +import axios, { type AxiosError, type InternalAxiosRequestConfig } from "axios"; |
| 2 | +import toast from "react-hot-toast"; |
| 3 | +import { ApiResponse } from "../schemas/api"; |
| 4 | +// Extend AxiosRequestConfig to include the _retry property |
| 5 | +interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig { |
| 6 | + _retry?: boolean; |
| 7 | +} |
| 8 | + |
| 9 | +const api = axios.create({ |
| 10 | + baseURL: process.env.NEXT_PUBLIC_CLIENTVAR, |
| 11 | +}); |
| 12 | + |
| 13 | +// Add a request interceptor |
| 14 | +api.interceptors.request.use( |
| 15 | + (config: CustomAxiosRequestConfig) => { |
| 16 | + config.withCredentials = true; |
| 17 | + |
| 18 | + return config; |
| 19 | + }, |
| 20 | + (error: AxiosError) => Promise.reject(error), |
| 21 | +); |
| 22 | + |
| 23 | +// Add a response interceptor |
| 24 | +api.interceptors.response.use( |
| 25 | + (response) => response, |
| 26 | + async (err) => { |
| 27 | + const error = err as AxiosError; |
| 28 | + const originalRequest = error.config as CustomAxiosRequestConfig; |
| 29 | + |
| 30 | + if (!error.response) { |
| 31 | + setTimeout(() => { |
| 32 | + window.location.href = "/"; |
| 33 | + }, 2000); |
| 34 | + } |
| 35 | + |
| 36 | + // If the error status is 401 and there is no originalRequest._retry flag, |
| 37 | + // it means the token has expired and we need to refresh it |
| 38 | + if (error.response?.status === 401 && !originalRequest._retry) { |
| 39 | + originalRequest._retry = true; |
| 40 | + |
| 41 | + try { |
| 42 | + await axios.post<ApiResponse>( |
| 43 | + `${process.env.NEXT_PUBLIC_CLIENTVAR}/token/refresh`, |
| 44 | + {}, |
| 45 | + { |
| 46 | + withCredentials: true, |
| 47 | + }, |
| 48 | + ); |
| 49 | + return api(originalRequest); // Use the api instance to retry the request |
| 50 | + } catch { |
| 51 | + // Handle refresh token error or redirect to login |
| 52 | + toast.error("Session expired. Please login again."); |
| 53 | + setTimeout(() => { |
| 54 | + window.location.href = "/"; |
| 55 | + }, 2000); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return Promise.reject(error); |
| 60 | + }, |
| 61 | +); |
| 62 | + |
| 63 | +export default api; |
0 commit comments