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.
- Read the body with res.text() and log the status plus the first 300 characters.
- Compare the requested URL with the real route (prefix, trailing slash, base URL).
- If the status is 401 or res.redirected is true, fix credentials or the auth redirect.
- If it is 502 or 504, debug the service behind the proxy.
- Parse JSON only after checking res.ok and the Content-Type header.
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;
}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.
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
- TypeError: fetch failed
- TypeError: Cannot read properties of undefined (reading 'x')
- Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
More in JSON, parsing and validation
- SyntaxError: Unexpected end of JSON inputNode.js
- TypeError: Converting circular structure to JSONNode.js
- ZodError: [ { "expected": "string", "code": "invalid_type", "path": [ "email" ]...Node.js
- RangeError: Invalid time valueNode.js
- json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)Python
- TypeError: Object of type datetime is not JSON serializablePython
- pydantic_core._pydantic_core.ValidationError: 1 validation error for User email Field...Python
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start bytePython
Other error topics
- 422 Unprocessable Entity: {"detail":[{"type":"missing","loc":["body","email"],"msg":"Field...Network and HTTP
- Error: connect ETIMEDOUT 10.0.4.12:5432Network and HTTP
- FunctionsHttpError: Edge Function returned a non-2xx status codeNetwork and HTTP
- PrismaClientInitializationError: Can't reach database server at `db.example.com:5432`Databases
- error: relation "todo" does not existDatabases
- sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due...Databases
- ImportError: attempted relative import with no known parent packageImports and modules
- Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported.Imports and modules
- Module not found: Can't resolve '@/components/OrderTable'Imports and modules
- Failed to find Server Action "7f3a9c2e5d1b4a6f8c0e2d7b9a1c3e5f7d9b0a2c4e". This request...React and Next.js rendering
- Error: Event handlers cannot be passed to Client Component props.React and Next.js rendering
- Too many re-renders. React limits the number of renders to prevent an infinite loop.React and Next.js rendering
- KeyError: 'email'Undefined, None and type errors
- TypeError: 'str' object is not callableUndefined, None and type errors
- TypeError: items is not iterableUndefined, None and type errors
- RuntimeWarning: coroutine 'fetch_user' was never awaitedMemory, async and the process
- Error: EACCES: permission denied, open '/app/data/cache.json'Memory, async and the process
- [UnhandledPromiseRejection: This error originated either by throwing inside of an async...Memory, async and the process
- Error: spawn npx ENOENTMCP servers and clients
- ModuleNotFoundError: No module named 'mcp.server.fastmcp'MCP servers and clients
- McpError: MCP error -32000: Connection closedMCP servers and clients
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.