import { cookies } from 'next/headers'; import { redirect } from 'next/navigation'; /** * Server-side fetch wrapper with authentication. */ export async function fetchServer( endpoint: string, options: RequestInit = {} ): Promise { const cookieStore = cookies(); const authToken = cookieStore.get('Authorization')?.value; if (!authToken) redirect('/login'); // Ensure the endpoint doesn't start with a slash if it's going to be appended to a URL that ends with one const cleanEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint; try { // Make sure we're using a complete URL (protocol + hostname + path) const apiUrl = process.env.SERVER_API_URL || 'https://internal-api.inboxi.ng/api'; // Ensure there's only one slash between the base URL and endpoint const url = apiUrl.endsWith('/') ? `${apiUrl}${cleanEndpoint}` : `${apiUrl}/${cleanEndpoint}`; console.log(`Making server request to: ${url}`); const res = await fetch(url, { ...options, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}`, ...options.headers, }, cache: 'no-store', }); if (res.status === 401) redirect('/login'); if (!res.ok) throw new Error(`Request failed: ${res.statusText}`); return res.json(); } catch (error) { console.error(`Server request to ${endpoint} failed:`, error); throw error; } }