Fix: SyntaxError: Unexpected token in JSON
Exact message
SyntaxError: Unexpected token < in JSON at position 0
Quick answer
This means JSON.parse() received a string that is not valid JSON. 'Unexpected token <' almost always means you received an HTML page (like a 404 or 500 error) instead of JSON.
🛠️ Fix it right here with AI Code Explainer
Edit the traceback below if needed, then let our AI suggest a fix without leaving this page.
Why this error happens
When fetch() or axios receives a response, you call .json() to parse it. If the server returns HTML (e.g., an error page) instead of JSON, the parser fails on the first character '<'.
Example: Wrong vs Right
Wrong
fetch('/api/data')
.then(res => res.json()) // Fails if server returns HTML
.then(data => console.log(data));Right
fetch('/api/data')
.then(res => {
if (!res.ok) throw new Error("Server error");
return res.json();
})
.catch(err => console.error("Not JSON:", err));How to fix it (step by step)
- Open the Network tab in DevTools
- Find the failing API request and look at the Response tab
- If it's HTML, your API route is returning an error page
- Check your API endpoint URL and the server logs
Frequently asked questions
Why does this happen with fetch()?
By default, fetch() does not reject the promise on HTTP errors like 404. It resolves, and you try to parse an HTML error page as JSON.
How do I safely parse JSON?
Wrap JSON.parse in a try/catch block, or check the Content-Type header before parsing.
Related Search Terms
Related JS errors
Need to fix JS code not just errors?
Use the free to paste any JS snippet and get a line-by-line explanation.
Want an AI with memory for your project?
MonsterX AI remembers your codebase across chats.