/** * lib/api.ts — Central axios instance. * * - Auto-attaches Authorization: Bearer to every request * - On 401 → clears localStorage and redirects to /login */ import axios from 'axios'; import { getToken, removeToken, removeUser } from './auth'; const DEFAULT_API_BASE_URL = 'http://localhost:8000'; const normalizeBaseUrl = (value: string) => { try { const parsed = new URL(value); if (typeof window !== 'undefined' && window.location.protocol === 'https:' && parsed.protocol === 'http:') { parsed.protocol = 'https:'; } return parsed.toString().replace(/\/+$/g, ''); } catch { const normalized = value.replace(/\/+$/g, ''); if (typeof window !== 'undefined' && window.location.protocol === 'https:' && normalized.startsWith('http://')) { return `https://${normalized.slice(7)}`; } return normalized; } }; export const getApiBaseUrl = () => { const configured = process.env.NEXT_PUBLIC_API_URL || process.env.NEXT_PUBLIC_API_BASE_URL; if (!configured) return DEFAULT_API_BASE_URL; return normalizeBaseUrl(configured); }; export const normalizeDownloadUrl = (downloadUrl: string) => { if (!downloadUrl) return downloadUrl; const resolved = downloadUrl.startsWith('/') ? `${getApiBaseUrl()}${downloadUrl}` : downloadUrl.replace(/^\/\//, 'https://'); try { const parsed = new URL(resolved); if (typeof window !== 'undefined' && window.location.protocol === 'https:' && parsed.protocol === 'http:') { parsed.protocol = 'https:'; } parsed.pathname = parsed.pathname.replace(/\/\/{2,}/g, '/'); return parsed.toString(); } catch { return resolved.replace(/^http:\/\//i, 'https://').replace(/([^:]\/)\/\//g, '$1'); } }; export const api = axios.create({ baseURL: getApiBaseUrl(), }); // Attach JWT and enforce HTTPS on every outgoing request api.interceptors.request.use((config) => { const token = getToken(); if (token) { config.headers.Authorization = `Bearer ${token}`; } // Upgrade http → https at request time so SSR-baked http:// URLs are fixed // before the browser blocks them as Mixed Content. if (typeof window !== 'undefined' && window.location.protocol === 'https:') { if (config.baseURL?.startsWith('http://')) { config.baseURL = 'https://' + config.baseURL.slice(7); } if (typeof config.url === 'string' && config.url.startsWith('http://')) { config.url = 'https://' + config.url.slice(7); } } return config; }); // On 401 → clear auth state and redirect to /login api.interceptors.response.use( (response) => response, (error) => { if (error.response?.status === 401) { removeToken(); removeUser(); if (typeof window !== 'undefined') { window.location.href = '/login'; } } return Promise.reject(error); } );