Common causes
1. The URL is wrong and the server sent a 404 page
A typo, a missing version prefix or a path that only exists in another environment returns the server’s HTML 404 page. fetch does not reject on HTTP errors, so check res.ok before parsing.
const res = await fetch('/api/v2/user');
const users = await res.json();const res = await fetch('/api/v2/users');
if (!res.ok) throw new Error(`GET /api/v2/users failed: ${res.status}`);
const users = await res.json();2. A relative URL resolved against the current page
Without a leading slash, api/users is resolved relative to the page, so on /dashboard/ the request goes to /dashboard/api/users. Single-page apps answer unknown paths with index.html, which starts with <!DOCTYPE html>. This is why a call can work on the home page and fail on a nested route.
const res = await fetch('api/users');const res = await fetch('/api/users');3. The dev server has no API proxy
In development, Vite, webpack-dev-server and Create React App serve index.html for any path they do not know. Without a proxy rule, /api calls never reach your backend. The mirror image also happens in production, when the static host has no route to the API.
export default {
server: { port: 5173 },
};export default {
server: {
port: 5173,
proxy: { '/api': 'http://localhost:8080' },
},
};4. An expired session redirected to a login page
Many apps answer an unauthenticated API call with a 302 redirect to the login form, and fetch follows it silently. The final status is 200, so res.ok passes. Check the content type so the real problem (the session) is reported instead of a parse error.
const data = await res.json();const type = res.headers.get('content-type') ?? '';
if (!type.includes('application/json')) {
throw new Error(`Expected JSON but got ${type} from ${res.url}`);
}
const data = await res.json();Work out which page you received
Open the failing request in the Network tab, or log res.status, res.url and res.redirected. The combination narrows it down quickly:
- 200 with
text/html, not redirected: a single-page app fallback, usually a wrong path or a missing dev proxy. - 200 with
text/htmlafter a redirect: a login or consent page.res.urlshows where you ended up. - 401 or 403 with HTML: an authentication gate, or a web application firewall challenge page.
- 404 with HTML: the path does not exist on that host. Compare it with the deployed routes.
- 500 with HTML: a framework’s error page. The body usually holds the stack trace you need.
- 502, 503 or 504 with HTML: a proxy or load balancer could not get an answer from the backend.
A debugging fetch that reads the body as text once and reports what it found is more useful than calling res.json() directly:
const res = await fetch(url, { headers: { Accept: 'application/json' } });
const text = await res.text();
let data;
try {
data = JSON.parse(text);
} catch {
throw new Error(`${res.status} from ${res.url}: ${text.slice(0, 200)}`);
}
Read a body only once. A second read fails with Body is unusable in Node or body stream already read in Chrome, so call res.clone() first if you need both forms. To read a long HTML reply, paste it into the HTML Formatter; like every PasteKit tool it runs in your browser, so a page containing session data is not uploaded.
What other HTTP clients do with an HTML body
The cause is identical everywhere, but the symptom is not:
- axios does not throw by default. It leaves the HTML in
response.dataas a string, so the failure appears later as something likedata.map is not a function. Checktypeof response.datawhen debugging. - Python requests raises
JSONDecodeError: Expecting value: line 1 column 1 (char 0). See the Python page. - aiohttp checks the header first:
ContentTypeError: Attempt to decode JSON with unexpected mimetype: text/html. - Go:
invalid character '<' looking for beginning of value. - Jackson:
Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false'). - System.Text.Json:
'<' is an invalid start of a value. - Newtonsoft.Json:
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
Fixing it on the server side
Client checks make the failure readable, but an API should not answer with HTML in the first place:
-
Exclude the API from the single-page fallback. In nginx, give the API its own location so
try_filesnever catches it:location /api/ { proxy_pass http://backend; } location / { try_files $uri /index.html; } -
Register API routes before any catch-all route in Express and similar frameworks, and return a JSON 404 for anything left under
/api. -
Return 401 for API calls, not a redirect. Keep the login redirect for page navigation only.
-
Send
Accept: application/json. Frameworks such as Laravel use that header to decide between a JSON error and an HTML error page. -
Add a JSON error handler, so an unexpected 500 keeps the same content type as a success.
Frequently asked questions
How do I see the HTML my code received?
Open the browser developer tools, go to the Network tab, click the request and open the Response panel. In code, call res.text() instead of res.json() and log the first few hundred characters.
Why does the API work in the browser address bar but not in my app?
The address bar sends your cookies and follows redirects visibly, and its URL is absolute. Your app may be calling a relative URL, missing an auth header, or hitting a different origin that returns an error page.
Does this error mean my server is down?
Not necessarily, but it can. Proxies and load balancers such as nginx or Cloudflare return HTML pages for 502 and 503 errors, so a failing backend also produces a < at position 0.
Why does the message show "<!DOCTYPE " with dots after it?
V8 quotes the start of the text it could not parse: ten characters, followed by dots when more text remains. A short body such as <html> is shown whole. The quoted text is a useful clue about what the server actually sent.
Can a repair tool fix this?
No, because nothing is wrong with the JSON: there is no JSON. PasteKit reports the < at line 1, column 1, and the real fix is to make the request reach an endpoint that returns JSON.