import { normalizeApiUrl, getAuthToken, createApiHeaders } from './api-utils'; /** * Simple client-side fetch function for making API calls with Authorization header. * Ensures all requests go through the Next.js API proxy. */ export async function clientFetch(url: string, options: RequestInit = {}): Promise { try { // Create headers with authentication const headers = createApiHeaders(null, options.headers as Record); // Normalize URL to ensure it uses the Next.js API proxy const fullUrl = normalizeApiUrl(url); const res = await fetch(fullUrl, { ...options, headers, credentials: 'include', }); if (!res.ok) { const errorData = await res.json().catch(() => ({})); const errorMessage = errorData.message || errorData.error || `Request failed: ${res.status} ${res.statusText}`; console.error('API Error:', { status: res.status, url: fullUrl, response: errorData, method: options.method || 'GET' }); throw new Error(errorMessage); } // Handle 204 No Content responses if (res.status === 204) { return {} as T; } return await res.json(); } catch (error) { console.error(`Client fetch error at ${url}:`, error); throw error; } } /** * Get a cookie value by name */ export function getCookie(name: string): string | undefined { return document.cookie .split('; ') .find(row => row.startsWith(`${name}=`)) ?.split('=')[1]; }