Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(client): actionable error when /api returns non-JSON (#257)

Tashfeenf52b6a7c1698
diff --git a/client/src/lib/api.ts b/client/src/lib/api.ts
index 4789a54e..319f9df0 100644
--- a/client/src/lib/api.ts
+++ b/client/src/lib/api.ts
@@ -18,12 +18,15 @@ export const UNAUTHORIZED_EVENT = 'freellmapi:unauthorized';
export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
const token = getToken();
const res = await fetch(`${BASE}${path}`, {
+ // `...options` first so an explicit method/body/signal applies, but headers
+ // are merged last — otherwise an options.headers would clobber the
+ // Content-Type and Authorization we set here.
+ ...options,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options?.headers,
},
- ...options,
});
if (res.status === 401) {
// Session missing/expired — drop the token and let the AuthGate re-render.
@@ -34,7 +37,21 @@ export async function apiFetch<T>(path: string, options?: RequestInit): Promise<
const body = await res.json().catch(() => ({ error: { message: res.statusText } }));
throw new Error(body.error?.message ?? `HTTP ${res.status}`);
}
- return res.json();
+ // A 200 whose body isn't JSON means this request never reached the API — the
+ // usual cause is a reverse proxy (or static host) serving the dashboard's
+ // index.html for /api/* instead of forwarding it to the backend. Without this
+ // guard the raw res.json() throws an opaque "Unexpected token '<'", which on
+ // the setup/login form surfaces as "sign up page cannot work". Say what's
+ // actually wrong. (#257)
+ const text = await res.text();
+ try {
+ return JSON.parse(text) as T;
+ } catch {
+ throw new Error(
+ `Expected JSON from ${path} but got a non-JSON response. The API isn't reachable at this origin — ` +
+ `make sure the backend is running and that /api is forwarded to it, not served as the dashboard's static files.`,
+ );
+ }
}
export async function logout(): Promise<void> {