This commit is contained in:
NotII
2025-03-10 17:39:37 +00:00
parent c08df8919d
commit 20d5559832
69 changed files with 7676 additions and 78 deletions

View File

@@ -1,6 +1,36 @@
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
/**
* Gets the base URL for server API requests with proper fallbacks
*/
function getBaseUrl() {
// For server components, we normally would use environment variables
// But we need to be careful with how they're accessed
// Try to get the API URL from environment variables
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
// We need to get the host from somewhere to construct the URL
// In production, we can rely on the VERCEL_URL or similar
if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}/api`;
}
// If we have a configured API URL, use that
if (apiUrl) {
// If it's already an absolute URL, use it
if (apiUrl.startsWith('http')) {
return apiUrl;
}
// Otherwise, it's likely a relative path like /api
return `http://localhost:3000${apiUrl.startsWith('/') ? apiUrl : `/${apiUrl}`}`;
}
// Last resort fallback for development
return 'http://localhost:3000/api';
}
/**
* Server-side fetch wrapper with authentication.
*/
@@ -14,8 +44,20 @@ export async function fetchServer<T = unknown>(
if (!authToken) redirect('/login');
try {
console.log(`${endpoint}`)
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
const baseUrl = getBaseUrl();
// Ensure endpoint doesn't start with a slash if baseUrl ends with one
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
// Ensure baseUrl ends with a slash if it doesn't already
const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
// Combine them to get a complete URL
const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
console.log(`Server fetch to: ${url}`);
const res = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',