const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080'; type ApiResponse = { data?: T; error?: string; message?: string; }; import { redirect } from 'next/navigation'; export async function fetchServerAPI( endpoint: string, token: string, method: string = 'GET', body?: object ): Promise> { const headers: Record = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }; const response = await fetch(`${BASE_URL}${endpoint}`, { method, headers, body: body ? JSON.stringify(body) : undefined, next: { tags: [endpoint] } }); if (!response.ok) { if (response.status == 401) { redirect('/login?expired=true'); } let message = response.statusText; try { const body = await response.json(); message = body?.error ?? body?.message ?? message; } catch { // non-JSON error body, keep statusText } throw new Error(message); } if (response.headers.get('Content-Type')?.includes('application/json')) { return { data: await response.json() }; } return { message: await response.text() }; }