Initial commit: Full project structure
- Backend: NestJS with Docker - Frontend: Next.js with Docker - Nginx configuration for reverse proxy - PostgreSQL setup - Docker compose for orchestration - Development environment configuration
This commit is contained in:
57
frontend/src/lib/api/client.ts
Normal file
57
frontend/src/lib/api/client.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
// src/lib/api/client.ts
|
||||
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
|
||||
import { ApiError } from '@/types';
|
||||
|
||||
interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
|
||||
_retry?: boolean;
|
||||
}
|
||||
|
||||
export const apiClient = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
||||
withCredentials: true, // ✅ REQUIRED FOR COOKIES
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// ❌ REMOVE request interceptor completely (no Authorization header)
|
||||
|
||||
// ✅ Response interceptor
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error: AxiosError) => {
|
||||
const originalRequest = error.config as CustomAxiosRequestConfig;
|
||||
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
// ✅ refresh via cookie (no body needed ideally)
|
||||
await axios.post(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/auth/refresh`,
|
||||
{},
|
||||
{ withCredentials: true }
|
||||
);
|
||||
|
||||
return apiClient(originalRequest);
|
||||
} catch (refreshError) {
|
||||
if (typeof window !== 'undefined') {
|
||||
return Promise.reject(error); // ✅ just fail silently
|
||||
}
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
|
||||
const apiError: ApiError = {
|
||||
statusCode: error.response?.status || 500,
|
||||
message:
|
||||
(error.response?.data as any)?.message ||
|
||||
error.message ||
|
||||
'An unexpected error occurred',
|
||||
error: (error.response?.data as any)?.error,
|
||||
};
|
||||
|
||||
return Promise.reject(apiError);
|
||||
}
|
||||
);
|
||||
Reference in New Issue
Block a user