Skip to content

SyntaxError: Unexpected token < in JSON

Error message

                Unexpected token < in JSON at position 0
              

Quick summary

You called JSON.parse() on a response that is HTML, not JSON — usually an API error page or a redirect to a login page.

Why this happens

  • The server returned an HTML error page instead of JSON

  • A fetch response was redirected to a login page (HTML)

  • The response content-type was not checked before parsing

Minimal example

✗ Broken code
const res = await fetch("/api/data");
const data = JSON.parse(await res.text());
✓ Fixed code
const res = await fetch("/api/data");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();

If the server returns HTML (e.g., a 404 page), JSON.parse fails on the < character. Check res.ok first and use res.json().

How to diagnose

  • Log the raw response text before parsing to see what was returned

  • Check the response status code and content-type header

  • Verify the API endpoint is correct and the server is running

How to fix

  • Check response.ok and response status before parsing

  • Verify the content-type is application/json before calling .json()

  • Handle non-JSON responses with an appropriate error message

How to prevent

  • Always check response.ok and content-type before parsing JSON

  • Use response.json() which handles content-type automatically

  • Log unexpected responses for debugging

Related Resources

Related Glossary

Related Lessons

Related Tools

← Back to language