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