Fortune-PlayLogic/lib/api.ts
2026-03-02 19:09:22 +03:00

51 lines
1.6 KiB
TypeScript

import axios from "axios";
// Create a configured Axios instance
const api = axios.create({
baseURL:
process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:8080/api/v1",
headers: {
"Content-Type": "application/json",
"ngrok-skip-browser-warning": "true",
},
});
// Request interceptor for adding the auth token
api.interceptors.request.use(
(config) => {
// Only access localStorage if we are running in the browser
if (typeof window !== "undefined") {
// const token = localStorage.getItem('token');
const token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmb3J0dW5lLWJldCIsImF1ZCI6WyJhcGkuZm9ydHVuZWJldHMubmV0Il0sImV4cCI6MTc3MjQ0NDk1NCwibmJmIjoxNzcyNDQ0MzU0LCJpYXQiOjE3NzI0NDQzNTQsIlVzZXJJZCI6NSwiUm9sZSI6ImN1c3RvbWVyIiwiQ29tcGFueUlEIjp7IlZhbHVlIjoxLCJWYWxpZCI6dHJ1ZX19.6CZQp4VL9ehBh2EfMEohkoVMezT_qFdXajCKsUmWda4";
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
},
);
// Response interceptor for handling common errors (like 401 Unauthorized)
api.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response?.status === 401) {
// Handle unauthorized errors, e.g., redirecting to login or clearing the token
if (typeof window !== "undefined") {
localStorage.removeItem("token");
// Uncomment the line below to redirect automatically
// window.location.href = '/login';
}
}
return Promise.reject(error);
},
);
export default api;