38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
import axios, { type AxiosError } from 'axios'
|
|
|
|
export const api = axios.create({
|
|
baseURL: process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:5089/api',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
|
|
// Inject auth token on every request
|
|
api.interceptors.request.use((config) => {
|
|
// TODO: replace with real token from cookie once auth is implemented
|
|
const token = typeof window !== 'undefined'
|
|
? document.cookie.split('; ').find(r => r.startsWith('access-token='))?.split('=')[1]
|
|
: null
|
|
if (token) config.headers.Authorization = `Bearer ${token}`
|
|
return config
|
|
})
|
|
|
|
// Normalize error responses
|
|
api.interceptors.response.use(
|
|
(res) => res,
|
|
(error: AxiosError<{ error: string }>) => {
|
|
const status = error.response?.status
|
|
if (status === 401) {
|
|
if (typeof window !== 'undefined') window.location.href = '/login'
|
|
return new Promise(() => {}) // redirect in progress — never resolve so no error toast fires
|
|
}
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
// Helper to extract error message from API response
|
|
export function getApiError(error: unknown): string {
|
|
if (axios.isAxiosError(error)) {
|
|
return error.response?.data?.error ?? error.message
|
|
}
|
|
return 'An unexpected error occurred'
|
|
}
|