SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Node.js · updated 2026-11-05

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.
typescript
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;
}
Fix it with your coding agent

Paste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.

prompttext
Read https://runheed.com/errors/unexpected-token-json.md and fix this error in this project.

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 '<'

Let your coding agent catch the next one

Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:

> Find the "Unexpected token '<'" JSON errors in production, find the calling code from each stack, and add a response check that throws with the status and a body preview before parsing.

Setup for Supabase Edge Functions, Vercel Functions or Cloudflare Workers, then have your agent fix and resolve it.

Related errors

More in JSON, parsing and validation

Other error topics

Free tools: Source map stack trace decoder · Uptime and SLA downtime calculator · Error budget calculator · Stack trace formatter · JSON log viewer · HTTP status code reference.

References: MDN: SyntaxError: JSON.parse: bad parsing, MDN: Response.json(), MDN: Response.ok

Spotted a mistake? Email hello@greatwork.company. About Runheed.