60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
// src/api.js
|
|
import axios from "axios";
|
|
import { redirect } from "react-router-dom"; // if using react-router
|
|
// or use your preferred navigation method
|
|
|
|
const api = axios.create({
|
|
baseURL: import.meta.env.VITE_BASE_URI,
|
|
withCredentials: true,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"ngrok-skip-browser-warning": "69420",
|
|
"Access-Control-Allow-Origin": "*"
|
|
},
|
|
|
|
});
|
|
|
|
// Flag to prevent infinite loop
|
|
let isRefreshing = false;
|
|
|
|
// Response interceptor
|
|
api.interceptors.response.use(
|
|
response => {
|
|
if (window.location.pathname === "/login" || window.location.pathname === "/register") {
|
|
window.location.href = "/";
|
|
}
|
|
return response;
|
|
},
|
|
async error => {
|
|
const originalRequest = error.config;
|
|
// Prevent multiple refresh attempts
|
|
if (error.response?.status === 401 || error.response?.status === 500) {
|
|
originalRequest._retry = true;
|
|
try {
|
|
if (!isRefreshing) {
|
|
isRefreshing = true;
|
|
// Attempt to refresh the token
|
|
const refreshResponse = await api.patch("/api/auth/refresh");
|
|
if (refreshResponse.status === 200) {
|
|
isRefreshing = false;
|
|
// Retry the original request
|
|
if (window.location.pathname === "/login" || window.location.pathname === "/register") {
|
|
window.location.href = "/"; // Redirect to login page
|
|
}
|
|
return api(originalRequest);
|
|
}
|
|
}
|
|
} catch (refreshError) {
|
|
console.error("Refresh token failed:", refreshError);
|
|
if (window.location.pathname !== "/login" && window.location.pathname !== "/register") {
|
|
window.location.href = "/login"; // Redirect to login page
|
|
}
|
|
}
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default api;
|