Initial commit
This commit is contained in:
42
src/lib/axios.ts
Normal file
42
src/lib/axios.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import axios from "axios";
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || "/api",
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
// Request interceptor to add auth token
|
||||
api.interceptors.request.use(
|
||||
(config) => {
|
||||
// Example: Add auth token from localStorage (replace with your auth logic)
|
||||
const token = localStorage.getItem("authToken");
|
||||
if (token) {
|
||||
config.headers["Authorization"] = `Bearer token`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Response interceptor for global error handling
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
// Example: Handle 401 Unauthorized globally
|
||||
if (error.response?.status === 401) {
|
||||
// Optionally, you can redirect to login page or show a toast
|
||||
console.error("Unauthorized - redirecting to login");
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.removeItem("authToken"); // Clear token on unauthorized
|
||||
window.location.href = "/login";
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
Reference in New Issue
Block a user