# SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON (Node.js)

Thrown by JSON.parse or response.json() when the body starts with '<', meaning an HTML document came back. Seen in Node services calling other APIs and in browser consoles when a fetch hits the wrong URL.

```
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:5738:19)
    at successSteps (node:internal/deps/undici/undici:5719:27)
    at fullyReadBody (node:internal/deps/undici/undici:4609:9)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async consumeBody (node:internal/deps/undici/undici:5728:7)
    at async loadOrders (/app/src/orders.js:11:16)
```

## Quick fix

Log the response status and the first few hundred characters of the body before parsing. What arrived is HTML: a 404 page, a proxy's 502 page, a login redirect or a framework error page. Fix the URL or the upstream failure, and only call res.json() when res.ok is true and the content type is JSON.

1. Read the body with res.text() and log the status plus the first 300 characters.
2. Compare the requested URL with the real route (prefix, trailing slash, base URL).
3. If the status is 401 or res.redirected is true, fix credentials or the auth redirect.
4. If it is 502 or 504, debug the service behind the proxy.
5. Parse JSON only after checking res.ok and the Content-Type header.

```ts
async function getJson<T>(url: string): Promise<T> {
  const res = await fetch(url, { headers: { accept: 'application/json' } });
  const type = res.headers.get('content-type') ?? '';
  if (!res.ok || !type.includes('application/json')) {
    const body = await res.text();
    throw new Error(`GET ${url} returned ${res.status} ${type}: ${body.slice(0, 300)}`);
  }
  return (await res.json()) as T;
}
```

## Why it happens

### Wrong URL hits an HTML 404 page

A missing /api prefix, a base URL from the wrong environment, or a typo routes the request to a path that does not exist. The server answers with its HTML not-found page, which begins with <!DOCTYPE.

### SPA fallback returns index.html

Dev servers and static hosts configured for client-side routing return index.html for unknown paths with status 200. res.ok is true, so status checks alone miss it; the content type gives it away.

### Proxy or gateway error page

nginx, a load balancer or a CDN sends its own HTML for 502 Bad Gateway or 504 Gateway Timeout when the API behind it is down or slow. Those pages often start with <html> instead of <!DOCTYPE.

### Redirect to a login page

An expired session or missing token makes the API redirect to a sign-in page. fetch follows redirects by default, so the code ends up parsing the login form HTML.

### Challenge, rate-limit or maintenance pages

WAF challenge screens, rate-limit responses and maintenance pages are HTML even on API paths. Some only appear for server-side traffic from cloud IP ranges, so the call works from a laptop and fails in production.

## Other fixes

- Send Accept: application/json so frameworks that negotiate content return JSON error bodies.
- Set redirect: 'manual' or 'error' on API calls so a login redirect fails loudly instead of returning HTML.
- Configure the dev server proxy so /api requests reach the backend instead of the HTML fallback.
- In server-side code, call shared logic directly rather than fetching your own API over HTTP.

## Same error, other wording

- `SyntaxError: Unexpected token < in JSON at position 0`
- `SyntaxError: Unexpected token '<', "<html>\r\n<h"... is not valid JSON`
- `SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data`
- `SyntaxError: JSON Parse error: Unrecognized token '<'`

## Sources

- [MDN: SyntaxError: JSON.parse: bad parsing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse)
- [MDN: Response.json()](https://developer.mozilla.org/en-US/docs/Web/API/Response/json)
- [MDN: Response.ok](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok)

---

To see this error the next time it happens in production, with the stack trace and the steps before it: Runheed records it and serves it to your coding agent over MCP. Setup instructions an agent can follow: https://runheed.com/SETUP.txt

Human-readable version: https://runheed.com/errors/unexpected-token-json
