Fix "Unexpected token '<', "<!DOCTYPE "... is not valid JSON"
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
- SyntaxError: Unexpected token < in JSON at position 0
- SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
- SyntaxError: JSON Parse error: Unrecognized token '<'
- SyntaxError: Unexpected end of JSON input
- SyntaxError: "undefined" is not valid JSON
Your code calls response.json() or JSON.parse(), but the server returned an HTML page (starting with <!DOCTYPE) instead of JSON. It is almost always a wrong URL (404), a server error (500) or a redirect to a login page: read the raw response to find out which.
What this error means
A valid JSON document starts with {, [, a quote, a number, true, false or null. The parser reads the first character it receives and, if it is <, it knows this is not JSON and throws a SyntaxError. That < is the start of <!DOCTYPE html> or <html>: the server answered with a web page. fetch does not reject on a 404 or 500 status, so your code tries to parse the error page as if everything was fine. "Unexpected end of JSON input" is the related case of an empty response.
Common causes
- Wrong URL: incorrect relative path, missing
/apiprefix or missing base URL. The server returns its HTML 404 page, or an SPA serves itsindex.html. - Server error: a PHP, Node.js or other exception produces an HTML 500 error page instead of a JSON response.
- Redirect to the login page: expired session or missing token, the auth middleware redirects to
/loginbecause the request does not sendAccept: application/json. - Empty response: a 204 status or empty body triggers "Unexpected end of JSON input".
- Double parsing:
JSON.parse()called on an already parsed object or onundefined(for examplelocalStorage.getItem()returningnull).
Step-by-step fix
-
Read the raw response
In the DevTools Network tab, click the request and check the status and the Response tab. Or log the raw text in your code before parsing it.
const res = await fetch('/api/users', { headers: { Accept: 'application/json' } }); const text = await res.text(); console.log(res.status, res.headers.get('content-type'), text.slice(0, 300)); -
Fix the URL
If the status is 404 or you get your own
index.html, the URL is wrong. Check the leading slash (/api/users, notapi/usersfrom a nested page), the API base URL and the dev proxy configuration. -
Check status and type before parsing
Wrap your calls in a function that throws a readable error when the response is not successful JSON. You will see the real server message instead of the
SyntaxError.async function getJson(url, options = {}) { const res = await fetch(url, { ...options, headers: { Accept: 'application/json', ...options.headers }, }); if (res.status === 204) return null; const type = res.headers.get('content-type') ?? ''; if (!res.ok || !type.includes('application/json')) { const body = await res.text(); throw new Error(`HTTP ${res.status} (${type}): ${body.slice(0, 200)}`); } return res.json(); } -
Make the server return JSON, even on errors
Always send
Accept: application/json: Laravel then returns its errors (401, 404, 422, 500) as JSON instead of redirecting or rendering a page. To force this on everyapi/*route, configurebootstrap/app.php(Laravel 11+).use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Http\Request; ->withExceptions(function (Exceptions $exceptions) { $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { return $request->is('api/*') || $request->expectsJson(); }); }) -
Fix double parsing
Only parse a JSON string.
response.json()already returns an object, do not pass it throughJSON.parse()again. ForlocalStorage, handle the missing value.const raw = localStorage.getItem('settings'); const settings = raw ? JSON.parse(raw) : {};
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Centralize network calls in a single function (or an axios instance) that always checks
res.okand thecontent-type. - On the API side, return a consistent JSON error body (
{ "message": "..." }) for every error, including 404 and 500. - Store the API base URL in an environment variable (
VITE_API_URL, for example) instead of building paths by hand.
Frequently asked questions
Why does it work locally but not in production?
In production the base URL, the proxy or the server rewrite rules often differ, so the request lands on the SPA HTML page or a 404 page. Compare the full URL being called in both environments.
What does "Unexpected end of JSON input" mean?
The parser received an empty string. The server answered with no body (often a 204 status): do not parse the response in that case.
Why doesn’t fetch throw on a 404?
fetch only rejects on a network failure. A 404 or 500 is a valid response: it is up to you to check res.ok or res.status.
Useful tools for this error
JSON validator
Validate, format and minify JSON, with the exact line and column of the error.
HTTP status codes
All the common HTTP codes (401, 403, 404, 419, 429, 500, 502…): meaning, causes and what to do.
Error finder
Paste an error message or a log: the tool recognises the error and opens the right fix.
More JavaScript & Node.js errors
- Fix "Cannot read properties of undefined" in JavaScript
- Fix "blocked by CORS policy: No 'Access-Control-Allow-Origin' header"
- Fix "Error: Cannot find module" in Node.js
- Fix "npm ERR! ERESOLVE unable to resolve dependency tree"
- Fix "Hydration failed because the server rendered HTML didn’t match the client" (React, Next.js)
- Fix "Too many re-renders. React limits the number of renders" in React
- Fix "Error: listen EADDRINUSE: address already in use" in Node.js
- Fix "SyntaxError: Cannot use import statement outside a module"