76 lines
2.2 KiB
TypeScript
76 lines
2.2 KiB
TypeScript
/**
|
|
* API utilities for consistent request handling
|
|
*/
|
|
|
|
/**
|
|
* Normalizes a URL to ensure it passes through the Next.js API proxy
|
|
* This ensures all client-side requests go through the Next.js rewrites.
|
|
*
|
|
* @param url The endpoint URL to normalize
|
|
* @returns A normalized URL with proper /api prefix
|
|
*/
|
|
export function normalizeApiUrl(url: string): string {
|
|
if (url.startsWith('/api/')) {
|
|
return url; // Already has /api/ prefix
|
|
} else {
|
|
// Add /api prefix, handling any leading slashes
|
|
const cleanUrl = url.startsWith('/') ? url : `/${url}`;
|
|
return `/api${cleanUrl}`;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Constructs a server-side API URL for backend requests
|
|
* Used in Server Components and API routes to directly access the backend API
|
|
*
|
|
* @param endpoint The API endpoint path
|
|
* @returns A complete URL to the backend API
|
|
*/
|
|
export function getServerApiUrl(endpoint: string): string {
|
|
const apiUrl = process.env.SERVER_API_URL || 'https://internal-api.inboxi.ng/api';
|
|
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
|
|
|
return apiUrl.endsWith('/')
|
|
? `${apiUrl}${cleanEndpoint}`
|
|
: `${apiUrl}/${cleanEndpoint}`;
|
|
}
|
|
|
|
/**
|
|
* Get the authentication token from cookies or localStorage
|
|
*/
|
|
export 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');
|
|
}
|
|
|
|
/**
|
|
* Check if the user is logged in
|
|
*/
|
|
export function isAuthenticated(): boolean {
|
|
return !!getAuthToken();
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
*/
|
|
export 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;
|
|
}
|