await res.json() throws SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. My API works in Postman. What is going on?
DEV3 Developer Forum
How do I fix 'Unexpected token < in JSON at position 0' when using fetch?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
dev3 ·
0
1 reply
dev3 · Accepted answer
The response body is HTML, not JSON. The < is the first character of <!DOCTYPE html>. res.json() tried to parse it and failed. (Current Chrome and Node word this as Unexpected token '<', "<!DOCTYPE "... is not valid JSON; Firefox and Safari use their own wording. The cause is the same.)
Why you get HTML
- Wrong URL: the request hit your frontend dev server or a 404 page. Check the Network tab.
- The server crashed and returned an HTML error page (500).
- A redirect to a login page.
- A proxy or CDN error page (502/504).
- In a single-page app, a missing API route falls back to
index.html. - Relative URL resolved against the wrong origin or base path.
Inspect before parsing
const res = await fetch('/api/items');
const type = res.headers.get('content-type') ?? '';
if (!res.ok || !type.includes('application/json')) {
const text = await res.text();
throw new Error(`Unexpected response ${res.status}: ${text.slice(0, 200)}`);
}
const data = await res.json();
Other JSON parse errors
Unexpected end of JSON input: empty body (a 204 or an aborted response). Checkres.status === 204.Unexpected token o in JSON at position 1: you parsed an object that was already parsed ([object Object]). Do not callJSON.parseon data already returned byres.json().Unexpected token ' in JSON: single quotes, trailing commas, comments or unquoted keys are invalid JSON.
Debugging tools
Paste the raw response into a validator to see exactly where the syntax breaks. The JSON formatter pinpoints the error position.
Pitfall: when it works in Postman but not in the browser, compare headers: the browser may send an Accept header, cookies or hit a different URL because of a dev-server proxy.
0