This commit is contained in:
NotII
2025-03-24 01:46:11 +00:00
parent 1e395b8684
commit 39c349509c
19 changed files with 477 additions and 427 deletions

View File

@@ -1,4 +1,47 @@
import { normalizeApiUrl, getAuthToken, createApiHeaders } from './api-utils';
/**
* Normalizes a URL to ensure it has the correct /api prefix
* This prevents double prefixing which causes API errors
*/
function normalizeApiUrl(url: string): string {
// Remove any existing /api or api prefix
const cleanPath = url.replace(/^\/?(api\/)+/, '');
// Add a single /api prefix
return `/api/${cleanPath.replace(/^\//, '')}`;
}
/**
* Get the authentication token from cookies or localStorage
*/
function getAuthToken(): string | null {
if (typeof document === 'undefined') return null; // Guard for SSR
return document.cookie
.split('; ')
.find(row => row.startsWith('Authorization='))
?.split('=')[1] || localStorage.getItem('Authorization');
}
/**
* Creates standard API request headers with authentication
*
* @param token Optional auth token (fetched automatically if not provided)
* @param customHeaders Additional headers to include
* @returns Headers object ready for fetch requests
*/
function createApiHeaders(token?: string | null, customHeaders: Record<string, string> = {}): Headers {
const headers = new Headers({
'Content-Type': 'application/json',
...customHeaders
});
const authToken = token || getAuthToken();
if (authToken) {
headers.set('Authorization', `Bearer ${authToken}`);
}
return headers;
}
/**
* Simple client-side fetch function for making API calls with Authorization header.
@@ -12,6 +55,8 @@ export async function clientFetch<T = any>(url: string, options: RequestInit = {
// Normalize URL to ensure it uses the Next.js API proxy
const fullUrl = normalizeApiUrl(url);
console.log(`Fetching URL: ${fullUrl}`);
const res = await fetch(fullUrl, {
...options,
headers,