DEV3 Technologies home

DEV3 Developer Forum

How do I fix 'Unexpected token < in JSON at position 0' when using fetch?

JavaScript helpSolved0 views
dev3 ·

await res.json() throws SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. My API works in Postman. What is going on?

#javascript#json#fetch#errors

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

  1. Wrong URL: the request hit your frontend dev server or a 404 page. Check the Network tab.
  2. The server crashed and returned an HTML error page (500).
  3. A redirect to a login page.
  4. A proxy or CDN error page (502/504).
  5. In a single-page app, a missing API route falls back to index.html.
  6. 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). Check res.status === 204.
  • Unexpected token o in JSON at position 1: you parsed an object that was already parsed ([object Object]). Do not call JSON.parse on data already returned by res.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

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.