/** * API utilities for client and server-side requests */ /** * Normalizes the API URL to ensure it uses the proper prefix * For client-side, ensures all requests go through the Next.js API proxy */ export function normalizeApiUrl(url: string): string { // If URL already starts with http or https, return as is if (url.startsWith('http://') || url.startsWith('https://')) { return url; } // If URL already starts with /api, use as is if (url.startsWith('/api/')) { return url; } // Otherwise, ensure it has the /api prefix return `/api${url.startsWith('/') ? '' : '/'}${url}`; } /** * Get the server API URL for server-side requests */ export function getServerApiUrl(endpoint: string): string { // Get the base API URL from environment const baseUrl = process.env.SERVER_API_URL || process.env.NEXT_PUBLIC_API_URL || 'https://internal-api.inboxi.ng/api'; // Ensure it doesn't have trailing slash const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl; // Ensure endpoint has leading slash const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`; return `${normalizedBaseUrl}${normalizedEndpoint}`; } /** * Get the authentication token from cookies or localStorage * Only available in client-side code */ export function getAuthToken(): string | null { if (typeof document === 'undefined') return null; return document.cookie .split('; ') .find(row => row.startsWith('Authorization=')) ?.split('=')[1] || (typeof localStorage !== 'undefined' ? localStorage.getItem('Authorization') : null); } /** * Create headers with authentication for API requests */ export function createApiHeaders(token: string | null = null, additionalHeaders: Record = {}): Headers { const headers = new Headers({ 'Content-Type': 'application/json', ...additionalHeaders }); // Use provided token or try to get it from storage const authToken = token || getAuthToken(); if (authToken) { headers.append('Authorization', `Bearer ${authToken}`); } return headers; }