client.ts47 lines, 1.1 KB
| 1 | import axios from "axios"; |
| 2 | |
| 3 | const BASE_URL = |
| 4 | process.env.NEXT_PUBLIC_API_URL || "http://localhost:8080/api/v1"; |
| 5 | |
| 6 | // function to get the current token |
| 7 | let getToken: () => string | null = () => { |
| 8 | if (typeof window === "undefined") return null; |
| 9 | return localStorage.getItem("token"); |
| 10 | }; |
| 11 | |
| 12 | // function to set the token |
| 13 | export const setTokenGetter = (fn: () => string | null) => { |
| 14 | getToken = fn; |
| 15 | }; |
| 16 | |
| 17 | export const apiClient = axios.create({ |
| 18 | baseURL: BASE_URL, |
| 19 | headers: { |
| 20 | "Content-Type": "application/json", |
| 21 | }, |
| 22 | }); |
| 23 | |
| 24 | // add a request interceptor |
| 25 | apiClient.interceptors.request.use((config) => { |
| 26 | const token = getToken(); |
| 27 | if (token) { |
| 28 | config.headers.Authorization = `Bearer ${token}`; |
| 29 | } |
| 30 | return config; |
| 31 | }); |
| 32 | |
| 33 | // add a response interceptor |
| 34 | apiClient.interceptors.response.use( |
| 35 | (response) => response, |
| 36 | (error) => { |
| 37 | if (typeof window !== "undefined" && error?.response?.status === 401) { |
| 38 | localStorage.removeItem("token"); |
| 39 | const isLoginPage = window.location.pathname.includes("/auth/login"); |
| 40 | if (!isLoginPage) { |
| 41 | window.location.href = "/auth/login"; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | return Promise.reject(error); |
| 46 | } |
| 47 | ); |