Unexpected token '<', "<!DOCTYPE" Is Not Valid JSON: Fixes

Dec 2, 2026 · 9 min read

Unexpected token '<', "<!DOCTYPE "... is not valid JSON means you got HTML: an error page, SPA fallback, wrong Content-Type or a login redirect. How to tell.

The laptop shop's product page worked on every developer machine and failed on staging with this in the console:

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

The message reads like a JSON bug, but the JSON parser is doing its job. It was asked to parse a response that starts with <!DOCTYPE, which means the server sent back an HTML page. The real question is never "what is wrong with my JSON?" but "why did I get HTML, and from whom?" There are four usual answers, and you can tell them apart in a minute once you look at the response instead of the error.

What the message is telling you

Chrome, Edge and Node print Unexpected token '<', "<!DOCTYPE "... is not valid JSON. The quoted part is the first ten characters of the text the parser received, and < is the first character it could not accept. Firefox says JSON.parse: unexpected character at line 1 column 1, one of the messages listed on MDN's JSON.parse error page. Python's version is Expecting value: line 1 column 1 (char 0). Different wording, same story: the body is not JSON at all, and it failed on the very first character.

The same family of errors shows up for plain-text error bodies. A proxy that answers with the words Not Found gives Unexpected token 'N', "Not Found" is not valid JSON, and a bare Internal Server Error gives Unexpected token 'I', "Internal S"... is not valid JSON. Whenever the quoted snippet reads like English or markup, stop debugging the parser and start debugging the request.

It usually comes from Response.json(), which reads the body and runs JSON.parse on it. Two things about that method cause most of the confusion. It does not look at the status code, so a 404 page gets parsed like any other body. And it does not look at the Content-Type header, so an HTML page gets parsed too.

Reproducing all four causes

To show the causes side by side, here is a tiny stand-in for the shop's backend. It has one real JSON endpoint, and it fails the way real servers, static hosts and SSO proxies fail:

js
// A small stand-in for the laptop shop: one real JSON endpoint and the four ways it goes wrong.
import http from 'node:http';

const html = (title) => `<!DOCTYPE html>\n<html lang="en"><head><title>${title}</title></head><body><h1>${title}</h1></body></html>`;

export const server = http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');

  if (url.pathname === '/api/laptops') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify([{ sku: 'LEN-T14-G5', model: 'ThinkPad T14 Gen 5', price: 1329 }]));
  }
  if (url.pathname === '/api/orders' && req.method === 'POST') {
    if (req.headers['content-type'] !== 'application/json') {
      res.writeHead(415, { 'Content-Type': 'text/html' });           // framework default error page
      return res.end(html('415 Unsupported Media Type'));
    }
    res.writeHead(201, { 'Content-Type': 'application/json' });
    return res.end('{"orderId":"ORD-20261202-0042","status":"created"}');
  }
  if (url.pathname === '/api/reports/assets') {
    res.writeHead(302, { Location: '/login?next=/api/reports/assets' }); // SSO proxy: not signed in
    return res.end();
  }
  if (url.pathname === '/login') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    return res.end(html('Sign in to Northwind IT'));
  }
  if (url.pathname.startsWith('/api/')) {
    res.writeHead(404, { 'Content-Type': 'text/html' });             // unknown API route
    return res.end(html('404 Not Found'));
  }
  res.writeHead(200, { 'Content-Type': 'text/html' });                // SPA fallback: index.html for every path
  res.end(html('Laptop Shop'));
});

Now the code most of us write first, calling res.json() straight away:

js
import { server } from './server.mjs';
await new Promise(r => server.listen(0, r));
const base = `http://localhost:${server.address().port}`;

const calls = [
  ['GET  /api/laptops        ', () => fetch(`${base}/api/laptops`)],
  ['GET  /api/laptop (typo)  ', () => fetch(`${base}/api/laptop`)],
  ['GET  /laptops.json (SPA) ', () => fetch(`${base}/laptops.json`)],
  ['POST /api/orders         ', () => fetch(`${base}/api/orders`, { method: 'POST', body: JSON.stringify({ sku: 'LEN-T14-G5', qty: 2 }) })],
  ['GET  /api/reports/assets ', () => fetch(`${base}/api/reports/assets`)],
];

for (const [label, call] of calls) {
  const res = await call();
  try {
    await res.json();
    console.log(label, res.status, 'parsed OK');
  } catch (err) {
    console.log(label, res.status, err.message);
  }
}
server.close();
text
GET  /api/laptops         200 parsed OK
GET  /api/laptop (typo)   404 Unexpected token '<', "<!DOCTYPE "... is not valid JSON
GET  /laptops.json (SPA)  200 Unexpected token '<', "<!DOCTYPE "... is not valid JSON
POST /api/orders          415 Unexpected token '<', "<!DOCTYPE "... is not valid JSON
GET  /api/reports/assets  200 Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Four different bugs, one identical error message. That is why this error wastes so much time.

1. The HTML error page

A typo in the path, a missing route after a deploy, or an exception in the handler. Most web frameworks and reverse proxies answer errors with an HTML page unless the request asks for JSON. The status code is 404 or 500, but because res.json() runs before anyone looks at res.status, the parse error is what you see.

2. The SPA fallback

Static hosts and dev servers for single-page apps are usually set up to answer every unknown path with index.html, so client-side routes work on refresh. Ask that host for /laptops.json or /api/laptops when the file or the proxy rule is missing, and you get the app's own HTML shell with status 200. This is the one that works locally, where a dev proxy forwards /api to the backend, and breaks on a static deploy where nothing does.

3. The wrong Content-Type on the request

This one is easy to miss. When you pass a string as the body, fetch sets the request's Content-Type to text/plain;charset=UTF-8, as the Fetch standard says. A backend that only accepts JSON then refuses the request, often with 415 Unsupported Media Type or a 400, and its default error page is HTML. The fix is one header: 'Content-Type': 'application/json'.

4. A proxy or SSO login page

Corporate networks and internal tools often sit behind a sign-in proxy. When your session cookie expires, the proxy answers your API call with a redirect to a login page. fetch follows redirects by default, so you end up with the login form and a status of 200. The giveaway is Response.redirected being true and res.url pointing at /login. Captive portals on hotel and conference Wi-Fi do the same thing to every request.

Look at the response before you parse it

The first move is always the same: see what actually came back. In the browser, open DevTools, go to the Network tab, click the request and read the Headers and Response panels. Check the status, the final URL, and the response Content-Type. From a terminal, curl -i prints the status line and headers above the body:

bash
$ curl -i http://localhost:8740/api/laptop
HTTP/1.1 404 Not Found
Content-Type: text/html
Date: Wed, 02 Dec 2026 21:25:32 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

<!DOCTYPE html>
<html lang="en"><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1></body></html>

For the redirect case, ask curl to follow redirects and print where it ended up:

bash
$ curl -s -o /dev/null -L -w '%{http_code} %{content_type} %{url_effective} redirects=%{num_redirects}\n' \
    http://localhost:8740/api/reports/assets
200 text/html http://localhost:8740/login?next=/api/reports/assets redirects=1

If you copy the body into the JSON validator it stops at line 1, column 1 with "Unexpected character '<'", which confirms you are looking at markup, not damaged JSON. If the body is JSON but the parse still fails further in, for example a hand-written mock with a trailing comma, the JSON fixer repairs that kind of syntax slip and shows you the corrected text.

A fetch helper that says what went wrong

In application code, read the body as text first, then decide. This helper checks for a redirect, checks the response Content-Type, parses inside its own try, and only then looks at res.ok, so a JSON error body from your API is still readable:

js
export async function fetchJson(url, options = {}) {
  const res = await fetch(url, {
    ...options,
    headers: { Accept: 'application/json', ...options.headers },
  });
  const type = res.headers.get('content-type') ?? '';
  const text = await res.text();

  if (res.redirected) {
    throw new Error(`Redirected to ${res.url} (a login page?) instead of returning JSON`);
  }
  if (!/\bjson\b/i.test(type)) {
    const start = text.slice(0, 80).replace(/\s+/g, ' ');
    throw new Error(`${res.status} from ${url}: expected JSON, got ${type || 'no Content-Type'}: ${start}`);
  }
  let data;
  try {
    data = JSON.parse(text);
  } catch (err) {
    throw new Error(`${res.status} from ${url}: body is not valid JSON (${err.message})`);
  }
  if (!res.ok) {
    throw new Error(`${res.status} from ${url}: ${JSON.stringify(data).slice(0, 200)}`);
  }
  return data;
}

Run against the same five calls, plus the order request with the header fixed:

js
import { server } from './server.mjs';
import { fetchJson } from './fetch-json.mjs';
await new Promise(r => server.listen(0, r));
const base = `http://localhost:${server.address().port}`;

const order = { sku: 'LEN-T14-G5', qty: 2 };
const calls = [
  () => fetchJson(`${base}/api/laptops`),
  () => fetchJson(`${base}/api/laptop`),
  () => fetchJson(`${base}/laptops.json`),
  () => fetchJson(`${base}/api/orders`, { method: 'POST', body: JSON.stringify(order) }),
  () => fetchJson(`${base}/api/orders`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(order),
  }),
  () => fetchJson(`${base}/api/reports/assets`),
];

for (const call of calls) {
  try {
    console.log('OK  ', JSON.stringify(await call()));
  } catch (err) {
    console.log('FAIL', err.message.replace(base, ''));
  }
}
server.close();
text
OK   [{"sku":"LEN-T14-G5","model":"ThinkPad T14 Gen 5","price":1329}]
FAIL 404 from /api/laptop: expected JSON, got text/html: <!DOCTYPE html> <html lang="en"><head><title>404 Not Found</title></head><body><
FAIL 200 from /laptops.json: expected JSON, got text/html: <!DOCTYPE html> <html lang="en"><head><title>Laptop Shop</title></head><body><h1
FAIL 415 from /api/orders: expected JSON, got text/html: <!DOCTYPE html> <html lang="en"><head><title>415 Unsupported Media Type</title><
OK   {"orderId":"ORD-20261202-0042","status":"created"}
FAIL Redirected to /login?next=/api/reports/assets (a login page?) instead of returning JSON

Each failure now names its own cause: the status, the URL and the start of the page. The <title> alone usually tells you which of the four you hit. Sending Accept: application/json also helps, since many frameworks pick a JSON error body over an HTML one when the client asks for it.

The same check in Python with requests, where r.json() raises JSONDecodeError on the HTML page:

python
import requests

r = requests.get("http://localhost:8740/api/laptop", headers={"Accept": "application/json"})
print(r.status_code, r.headers.get("Content-Type"))

try:
    r.json()
except requests.exceptions.JSONDecodeError as e:
    print("JSONDecodeError:", e)

if "json" not in r.headers.get("Content-Type", ""):
    print("Not JSON. Body starts with:", r.text[:15])
text
404 text/html
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Not JSON. Body starts with: <!DOCTYPE html>

Fixing the cause, not the symptom

  • 404 or 500 HTML page: fix the URL or the route. Check for a missing /api prefix, a version segment, or a trailing slash rule that redirects. Make the API return JSON errors for /api/*.
  • SPA fallback with status 200: the request never reached the backend. Add the proxy or rewrite rule for /api/* on the host, or call the API on its own origin. Ask the host to return a real 404 for missing files under /api.
  • 415 or 400 on POST: send Content-Type: application/json with a JSON body. Passing a plain object as body does not work either; stringify it.
  • Redirect to a login page: the session expired or the request went out without credentials. Use credentials: "include" for cross-origin cookies, or send the token the API expects, and treat res.redirected as "sign in again".

What not to do: wrap res.json() in a try that swallows the error and returns an empty array. The page then renders "No laptops found" while the real problem, a broken route or an expired session, stays hidden until a customer reports it.

Wrapping up

Unexpected token '<' means you parsed HTML. Look at the status, the final URL and the Content-Type before you look at your JSON. A 404 or 500 page means a wrong route or a server error, a 200 HTML shell means an SPA fallback, a 415 means a missing request header, and a redirect means a login page. Read the body as text, check what it is, then parse it. When you do have the right JSON and just want to see what is in it, you can paste it into the JSON parser and read it as a table.

← All JSON articles Browse all categories →