diff --git a/lib/client-service.ts b/lib/client-service.ts index 10c91d6..3798c32 100644 --- a/lib/client-service.ts +++ b/lib/client-service.ts @@ -11,25 +11,65 @@ interface FetchOptions { headers?: HeadersInit; } +// Helper function to get auth token from cookies +function getAuthToken(): string | null { + if (typeof document === 'undefined') return null; // Guard for SSR + + return document.cookie + .split('; ') + .find(row => row.startsWith('Authorization=')) + ?.split('=')[1] || null; +} + export async function fetchClient( endpoint: string, options: FetchOptions = {} ): Promise { const { method = 'GET', body, headers = {}, ...rest } = options; + // Get the base API URL from environment or fallback const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'; - // Check if endpoint already includes /api - const apiPrefix = endpoint.includes('/api/') ? '' : '/api'; - const url = `${apiUrl}${apiPrefix}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`; + // Ensure the endpoint starts with a slash + const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`; + + // For the specific case of internal-api.inboxi.ng - remove duplicate /api + let url; + if (apiUrl.includes('internal-api.inboxi.ng')) { + // Special case for internal-api.inboxi.ng + if (normalizedEndpoint.startsWith('/api/')) { + url = `${apiUrl}${normalizedEndpoint.substring(4)}`; // Remove the /api part + } else { + url = `${apiUrl}${normalizedEndpoint}`; + } + } else { + // Normal case for other environments + url = `${apiUrl}${normalizedEndpoint}`; + } + + // Get auth token from cookies + const authToken = getAuthToken(); + + // Prepare headers with authentication if token exists + const requestHeaders: Record = { + 'Content-Type': 'application/json', + ...(headers as Record), + }; + + if (authToken) { + requestHeaders['Authorization'] = `Bearer ${authToken}`; + } + + console.log('API Request:', { + url, + method, + hasAuthToken: !!authToken + }); const fetchOptions: RequestInit = { method, credentials: 'include', - headers: { - 'Content-Type': 'application/json', - ...headers, - }, + headers: requestHeaders, ...rest, };