fetch fails with Unexpected token '<', "<!DOCTYPE "... is not valid JSON: tracking down why HTML comes back instead of JSON
fetch().then(res => res.json()) throws SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON because the URL you called as an API returned HTML. I reproduced the four usual causes in Node.js and Chromium (a relative path resolving somewhere else, an SPA falling back to index.html, an HTML 500 error page, and a redirect to the login page), and show how to check what actually came back with the Network tab and res.text(). Also covers Unexpected end of JSON input, "undefined" is not valid JSON, and Python's Expecting value: line 1 column 1.
I wrote some code that calls an API from a page, ran it, and the browser console said this.
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
The code was the usual fetch(url).then(res => res.json()). Suspecting I had written the JSON wrong, I went over the server code and found nothing odd. Of course not: this error is not about a JSON syntax mistake. It tells you that HTML arrived where JSON was expected. The < is the first character of the <!DOCTYPE html> or <html> at the top of an HTML document, and the "<!DOCTYPE "... in the message is simply the first ten characters of the string that was received.
So what needs fixing is not the JSON parsing but the question of why that URL returned HTML. In this article I reproduce the four situations that cause it most often, show how to check what actually came back, and go through how to read similar messages.
The output in this article comes from Node.js 22.23.5 and Chromium 158, run against a small test server written with Node.js’s http module. The server returns JSON only for /api/data.json, and for every other path it returns index.html, the way a single-page application (SPA) server does.
Reading the message: what you see is the start of the received string
res.json() reads the response body to the end and passes the string to JSON.parse(). A JSON value starts with {, [, ", a digit, or true, false or null, so parsing fails as soon as the first character is <. V8 (the JavaScript engine in Chrome, Edge and Node.js) puts the character it could not read and the beginning of the input into the message.
With the same test server, these are the messages I got when changing what it returned.
| Start of the received body | Message |
|---|---|
<!DOCTYPE html>... |
Unexpected token '<', "<!DOCTYPE "... is not valid JSON |
<html><body><h1>500 ... |
Unexpected token '<', "<html><bod"... is not valid JSON |
| Empty (204 No Content) | Unexpected end of JSON input |
In other words, "<!DOCTYPE "... most likely means a full, proper HTML page came back, while something like "<html><bod"... points to a bare-bones HTML page such as an error page. The second half of the message alone gives you a good idea of what you received.
Older Chrome versions and Node.js 18 show Unexpected token < in JSON at position 0 in the same situation. Only the wording differs; the meaning is the same. Firefox says JSON.parse: unexpected character at line 1 column 1 of the JSON data.
First, look at what actually came back
Before guessing at the cause, check what really arrived. In the browser, the Network tab of the developer tools is the fastest way.
- Open the developer tools with F12 and select the Network tab.
- Choose “Fetch/XHR” in the filter at the top, then reload the page or repeat the action that calls the API.
- Select the request in the list and, under Headers, look at the Request URL, the Status Code and the Content-Type response header.
- Look at the body under Response (or Preview).
If the Request URL is not what you expected, the problem is how the URL is built. If the Status Code is 404 or 500, the problem is on the server. If the status is 200 but the Content-Type is text/html, the request has ended up on a path that serves HTML.
To check from code, receive the body as a string with res.text() instead of res.json(), and print it together with the status and the final URL.
const res = await fetch(url);
console.log(res.status, res.url, res.headers.get('content-type'));
console.log((await res.text()).slice(0, 300));
res.url is the URL after any redirects were followed, so this is where you notice, for example, that you were sent to the login page. Keep in mind that a response body can only be read once: calling res.json() after res.text() throws an error.
Cause 1: a relative path resolves somewhere you did not expect
This is the easiest one to overlook. A path without a leading /, as in fetch('api/data.json'), is resolved against the URL of the page currently open. When you test on the top page /, it becomes /api/data.json and works, but run the same code on the /users/123 page and the request goes to /users/api/data.json.
I opened http://localhost:8080/users/123 in Chromium and fetched with two different paths. The request URLs and results were these.
fetch('api/data.json') → http://localhost:8080/users/api/data.json
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
fetch('/api/data.json') → http://localhost:8080/api/data.json
{"items":[1,2]}
There is no file at /users/api/data.json, but because this server answers unknown paths with index.html, it did not even return 404; it returned HTML with status 200. If the symptom is “works on the top page, breaks when I move to another page”, suspect this first.
The fix is to write the path from the site root, as in /api/data.json, or to keep the API base URL as a setting and build URLs with an explicit base, as in new URL('api/data.json', API_BASE).
Cause 2: a URL that does not exist gets the SPA’s index.html
An SPA built with React, Vue and the like handles page URLs such as /users/123 with a router in the browser. For that reason, servers and dev servers are often configured to “return index.html even for paths where no file exists”. Examples are historyApiFallback in webpack-dev-server, and Cloudflare Pages, which treats a site without a 404.html as an SPA and returns index.html.
Under that setup, getting a single character of the API URL wrong does not produce a 404. On the test server, calling /api/data with the extension forgotten, instead of the correct /api/data.json, gave this.
/api/data 200 text/html; charset=utf-8
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
The status is 200, so a res.ok check alone lets it through. If the Network tab shows a Content-Type of text/html, suspect this pattern.
A common case during development is running the frontend dev server (say, localhost:5173) and the API server (say, localhost:8080) separately, so that fetch('/api/...') lands on the frontend dev server. The dev server does not know /api/... and returns index.html. You need to forward /api to the API server with server.proxy in Vite or devServer.proxy in webpack-dev-server. The familiar “it works in production” difference, where production sits behind a reverse proxy or serves everything from one domain, also comes from this.
Cause 3: the server hit an error and returned an HTML error page
Even with the right URL, when the API throws an exception, the framework or web server may return an HTML error page. This is what happened when the test server returned a 500.
/api/error 500 text/html
SyntaxError: Unexpected token '<', "<html><bod"... is not valid JSON
Here the SyntaxError shown on the client is a secondary symptom; the real error is in the server log. nginx’s 502 Bad Gateway and the error pages of load balancers and CDNs come back as HTML in the same way. Calling res.json() without looking at the status throws away the crucial information, the 500 or the 502, and leaves you with only the SyntaxError.
Cause 4: the session expired and you were redirected to the login page
If you call an API after your session has expired, the server may redirect you to the login page with a 302. fetch() follows redirects automatically by default, so what you receive is the HTML of the login page at the redirect target.
fetch('/api/private') → status 200, res.url = http://localhost:8080/login
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
The final status is 200, res.redirected is true, and res.url is the login page URL. If it only happens in a tab that has been left alone for a while and logging in again fixes it, this is your cause. If the API returns a 401 with JSON instead of redirecting when the user is not authenticated, the client has a much easier time handling it.
Preventing it: check the status and Content-Type before res.json()
Whatever the cause, if you check the status and Content-Type before parsing instead of calling res.json() directly, the error message tells you what came back.
async function fetchJson(url, options) {
const res = await fetch(url, options);
const type = res.headers.get('content-type') || '';
const body = await res.text();
if (!res.ok || !type.includes('json')) {
throw new Error(
`${res.status} ${res.statusText} ${res.url} (${type || 'no Content-Type'})\n` +
body.slice(0, 200)
);
}
return body ? JSON.parse(body) : null;
}
Using this function in the four situations above produced errors like these instead of a SyntaxError.
Error: 200 OK http://localhost:8080/api/data (text/html; charset=utf-8)
<!DOCTYPE html>
<html><head><title>App</title></head><body><div id="root"></div></body></html>
Error: 500 Internal Server Error http://localhost:8080/api/error (text/html)
<html><body><h1>500 Internal Server Error</h1></body></html>
Error: 200 OK http://localhost:8080/login (text/html; charset=utf-8)
<!DOCTYPE html>
...
With the URL, status, Content-Type and the start of the body in front of you, you can almost always tell which of the four cases you are in. The Content-Type check uses includes('json') so that error formats such as application/problem+json also pass. Returning null for an empty body guards against the 204 case described next.
Reading similar messages
When the first character is not <, the mechanism is the same: the second half of the message shows the start of the input. Here is what Node.js 22 reports when various inputs are passed to JSON.parse().
| Message | What was passed | Common cause |
|---|---|---|
Unexpected end of JSON input |
An empty string | res.json() was called on a 204 No Content or other response without a body |
"undefined" is not valid JSON |
undefined |
A missing property or the return value of a function that returns nothing was passed |
"[object Object]" is not valid JSON |
An object | A value that was already an object was passed to JSON.parse() again |
Expected property name or '}' in JSON at position 1 (line 1 column 2) |
{'a':1} |
Keys were written with single quotes |
Expected double-quoted property name in JSON at position 7 (line 1 column 8) |
{"a":1,} |
There is a trailing comma |
Unexpected non-whitespace character after JSON at position 8 (line 2 column 1) |
A string with one JSON value per line | JSON Lines (NDJSON) was parsed in one go |
Unexpected token '', "{"ok":true}" is not valid JSON |
A string starting with a BOM | A UTF-8 file with a BOM was read and parsed as is |
The BOM case is confusing because the quotes appear to have nothing between them. In Node.js, fs.readFileSync(path, 'utf8') keeps the BOM, so strip it with text.replace(/^/, '') before parsing. res.json() and res.text() in fetch(), on the other hand, strip a UTF-8 BOM when reading, so the same content received over HTTP did not cause an error. How files with a BOM come about is also covered in a Japanese-language article, PythonでCSVを読むと UnicodeDecodeError になる (on the UnicodeDecodeError you get when reading a CSV in Python, available in Japanese only).
Note that "undefined" is not valid JSON is different from the null that localStorage.getItem() returns when there is no value. JSON.parse(null) returns null without an error. undefined gets passed when you hand over a property that does not exist, or the return value of a function that returns nothing.
In Python requests: Expecting value: line 1 column 1
Call the same URL from Python with requests, and the message changes to this.
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Expecting value means “at the position where a JSON value should start, there was a character that cannot be read as a value”, and line 1 column 1 says it failed on the very first character. You get the same message whether HTML came back or the body was empty, so it gives you fewer clues than the JavaScript version. The way to check is the same: print r.status_code, r.url, r.headers.get('Content-Type') and r.text[:300].
The order for narrowing down the cause
- Look at the second half of the message.
"<!DOCTYPE "means an HTML page,"<html>..."an error page, andend of JSON inputan empty body. - Look at the Network tab (or, in code,
res.url,res.statusand the Content-Type). - The Request URL is not what you expected → check how relative paths resolve, or the dev server’s proxy settings.
- Status 200 with a Content-Type of
text/html→ either the SPA’sindex.htmlis being returned for a URL that does not exist, or you were redirected to the login page.res.redirectedtells them apart. - Status 4xx or 5xx → look for the real error in the server log.
When you want to examine received JSON calmly, paste the string you got from res.text() into the JSON Formatter / Validator to read it while seeing where the syntax breaks. How to use it is explained in Format JSON and copy a value’s JSON Pointer.
Reproducing it yourself
With Node.js 18 or later, the following files reproduce the output in this article. server.mjs returns JSON only for /api/data.json; apart from the 204, 500 and 302 examples, every other path gets HTML equivalent to index.html.
// server.mjs
import http from 'node:http';
const html = '<!DOCTYPE html>\n<html><head><title>App</title></head><body><div id="root"></div></body></html>\n';
http.createServer((req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
if (pathname === '/api/data.json') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end('{"items":[1,2]}\n');
}
if (pathname === '/api/empty') { res.writeHead(204); return res.end(); }
if (pathname === '/api/error') {
res.writeHead(500, { 'Content-Type': 'text/html' });
return res.end('<html><body><h1>500 Internal Server Error</h1></body></html>');
}
if (pathname === '/api/private') {
res.writeHead(302, { Location: '/login' });
return res.end();
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);
}).listen(8080);
// check.mjs
for (const p of ['/api/data.json', '/api/data', '/api/empty', '/api/error', '/api/private']) {
const res = await fetch('http://localhost:8080' + p);
console.log(p, res.status, res.url, res.headers.get('content-type'));
try { console.log(' ', await res.json()); }
catch (e) { console.log(' ', e.name + ': ' + e.message); }
}
node server.mjs &
node check.mjs
To check the relative path example, keep the server running, open http://localhost:8080/users/123 in the browser, and run await (await fetch('api/data.json')).json() and await (await fetch('/api/data.json')).json() in the developer tools console.