/** * Client-side API utilities with authentication handling */ const getAuthToken = (): string | null => { const token = document.cookie .split('; ') .find(row => row.startsWith('Authorization=')) ?.split('=')[1]; return token || null; // Return null instead of throwing an error }; export const fetchClient = async ( endpoint: string, options: RequestInit = {} ): Promise => { try { const authToken = getAuthToken(); if (!authToken) { console.warn("No authentication token found. Redirecting to login..."); window.location.href = "/login"; return Promise.reject("Unauthorized"); } const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, { ...options, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}`, ...options.headers, }, credentials: 'include', }); if (!res.ok) { const errorData = await res.json(); throw new Error(errorData.message || `Request failed: ${res.statusText}`); } return res.json(); } catch (error) { console.error(`API request to ${endpoint} failed:`, error); throw error; } };