Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

response.json() fails with Unexpected token '<' because Express sent HTML

ErrorUnexpected token '<', "<!DOCTYPE "... is not valid JSON

Short answer

The browser got an HTML page where your code expected JSON, and response.json() choked on the first < character. The page is usually Express's own 404 or error page, or an index.html served for a wrong URL. Check the status and body of the real response, correct the URL, and make errors return JSON.

  • Applies to Express 5, Node.js 22, Chrome, Firefox
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Request the exact URL your code calls and look at the status line, the Content-Type and the first lines of the body. If it says text/html, the cause is on the server side of that URL.

    curl -i http://localhost:3000/api/users
  2. 2Match what you see, then jump to its fix

    1. 1Status 404 and a body that is not JSONThe URL does not match any route, so Express answers with its default 404Fix
    2. 2Status 500 and a body with an HTML stack trace (or a short HTML status message in production)A route threw an error and Express sent its default HTML error pageFix
    3. 3The failing call has no status check; fetch resolved even though the status was 404 or 500The client never checked the response before parsing itFix

What does the error look like?

  • Unexpected token '<', "<!DOCTYPE "... is not valid JSON
  • SyntaxError ... Unexpected token < when calling response.json()

Cause 1 of 3

The URL does not match any route, so Express answers with its default 404

1Check

In Express a 404 means every middleware and route ran and none responded, and the default reply is not JSON. A missing /api prefix, a wrong method or a route mounted on a different path all end here.

curl -i http://localhost:3000/api/users
grep -rn "app.use('/api\|router.get\|app.get" src/

2Fix

Fix the URL or the route so they match, then confirm the method too. A JSON 404 is easier to read than a page, so add a catch-all that returns one.

app.use((req, res) => {
  res.status(404).json({ error: `Not found: ${req.originalUrl}` });
});

3Verify

Call the corrected URL and see JSON, then call a wrong URL and see the JSON 404.

curl -i http://localhost:3000/api/users
curl -i http://localhost:3000/api/nope

Confirmed by expressjs.com

Did this fix it?

Cause 2 of 3

A route threw an error and Express sent its default HTML error page

1Check

The built-in error handler replies with HTML: the stack trace outside production and the status text when NODE_ENV is production.

curl -i http://localhost:3000/api/users | head -n 20

2Fix

Add an error-handling middleware with four arguments, after all routes, that answers with JSON and keeps the status in the 4xx or 5xx range.

app.use((err, req, res, next) => {
  if (res.headersSent) return next(err);
  const status = err.status || err.statusCode || 500;
  res.status(status >= 400 && status < 600 ? status : 500)
     .json({ error: err.message || 'Internal Server Error' });
});

3Verify

Force an error in a route and confirm the body is JSON.

curl -i http://localhost:3000/api/boom

Confirmed by expressjs.com

Did this fix it?

Cause 3 of 3

The client never checked the response before parsing it

1Check

fetch() resolves for HTTP error statuses too. response.ok is false for anything outside 200-299, so only a check stops you parsing an error page as JSON.

grep -rn "\.json()" src/

2Fix

Test response.ok first, then read the body as text for the error message when it fails.

const res = await fetch('/api/users');
if (!res.ok) throw new Error(`HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
const data = await res.json();

3Verify

Call a broken URL. You should see HTTP 404 with a short text snippet, not a JSON syntax error.

curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/api/nope

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Put a JSON 404 handler and a JSON error handler at the end of the API router.
  • Use one place in the client for fetch calls that checks response.ok before .json().
  • Keep API routes under a prefix so a wrong path cannot be confused with a page.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.