response.json() fails with Unexpected token '<' because Express sent HTML
Unexpected token '<', "<!DOCTYPE "... is not valid JSONShort 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.
Fix it fast
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/users2Match what you see, then jump to its fix
- 1
Status 404 and a body that is not JSONThe URL does not match any route, so Express answers with its default 404Fix - 2
Status 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
The failing call has no status check; fetch resolved even though the status was 404 or 500The client never checked the response before parsing itFix
- 1
What does the error look like?
Unexpected token '<', "<!DOCTYPE "... is not valid JSONSyntaxError ... 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/nopeConfirmed by expressjs.com
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 202Fix
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/boomConfirmed by expressjs.com
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/nopeConfirmed by developer.mozilla.org
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
Back end
Express answers Cannot GET for a page that should exist
Cannot GET /api/users
Cannot GET is Express's default reply when no route or static file matches the request.
4 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fix