fix(frontend): resolve API base URL at request time for production
Use same-origin /api in the browser so builds are not stuck with baked-in localhost. Server-side fetches use INTERNAL_API_URL, NEXT_PUBLIC_API_URL, or loopback. Centralize logic in lib/api-base.ts. Made-with: Cursor
This commit is contained in:
12
frontend/lib/api-base.ts
Normal file
12
frontend/lib/api-base.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/** Browser: `/api/...` (same origin). Server: INTERNAL_API_URL → NEXT_PUBLIC_API_URL → loopback. */
|
||||
export function apiUrl(path: string): string {
|
||||
const p = path.startsWith("/") ? path : `/${path}`;
|
||||
if (typeof window !== "undefined") {
|
||||
return `/api${p}`;
|
||||
}
|
||||
const base =
|
||||
process.env.INTERNAL_API_URL ||
|
||||
process.env.NEXT_PUBLIC_API_URL ||
|
||||
"http://127.0.0.1:4000/api";
|
||||
return `${base}${p}`;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:4000/api";
|
||||
import { apiUrl } from "./api-base";
|
||||
|
||||
async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const token = typeof window !== "undefined" ? localStorage.getItem("bbe_token") : null;
|
||||
@@ -8,7 +8,7 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
...options?.headers,
|
||||
};
|
||||
|
||||
const res = await fetch(`${API_URL}${path}`, { ...options, headers });
|
||||
const res = await fetch(apiUrl(path), { ...options, headers });
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ message: "Request failed" }));
|
||||
throw new Error(error.message || `HTTP ${res.status}`);
|
||||
@@ -128,7 +128,7 @@ export const api = {
|
||||
const token = typeof window !== "undefined" ? localStorage.getItem("bbe_token") : null;
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
const res = await fetch(`${API_URL}/media/upload`, {
|
||||
const res = await fetch(apiUrl("/media/upload"), {
|
||||
method: "POST",
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
body: formData,
|
||||
|
||||
Reference in New Issue
Block a user