Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions apps/frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import axios from 'axios';
import { useAuthStore } from '@/store/authStore';
import { useCurrentUserStore } from '@/store/currentUserStore';

const AUTH_401_TRIGGERS = /^\/(auth\/me|users\/me|users\/me\/)/;

/**
* The global Axios instance for making HTTP requests.
* * Pre-configured with the backend base URL and standard headers.
* Use this instance instead of `axios` directly to ensure consistent behavior.
*/
const api = axios.create({
baseURL: '/api',
headers: {
Expand All @@ -14,20 +12,22 @@ const api = axios.create({
timeout: 5000,
});

// Request interceptor → attach token
api.interceptors.request.use((config) => {
const token = useAuthStore.getState().token;
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});

// Response Interceptor
api.interceptors.response.use(
(response) => response,
(error: unknown) => {
if (axios.isAxiosError(error)) {
if (error.response?.status === 401) {
console.warn('Unauthorized! Redirecting to login...');
const url = error.config?.url ?? '';
if (AUTH_401_TRIGGERS.test(url)) {
useAuthStore.getState().clearAuthenticated();
useCurrentUserStore.getState().clearUser();
}
}
return Promise.reject(error);
}
Expand Down
Loading