SyntaxError: JSON 🟨 JavaScript

SyntaxError: Unexpected token < in JSON at position 0

JSON.parse() / response.json() received something that isn’t JSON — very often an HTML error page.

Seen on: JavaScript PHP React

Meaning

The < at position 0 is the start of <!DOCTYPE html> or <html>: the server returned an HTML page (404, 500, login redirect, SPA fallback) where your code expected JSON. Newer browsers say “Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON”.

Common causes

  • Wrong API URL — the request hits the frontend’s index.html fallback
  • Server error returned an HTML error page (500, 502, 404)
  • Authentication redirect to a login page
  • Dev server not proxying /api to the backend
  • PHP warnings/notices printed before the JSON output
  • Empty response body (“Unexpected end of JSON input”)

⚡ Quick fix

  1. Log await res.text() instead of res.json() to see what actually came back
  2. Check res.ok and Content-Type before parsing
  3. Verify the full request URL in the Network tab
  4. Turn off display_errors in production PHP so warnings don’t corrupt JSON

Detailed fix by platform

JavaScript

  1. Parse defensively:
    javascript
    const res = await fetch('/api/items');
    const type = res.headers.get('content-type') || '';
    if (!res.ok || !type.includes('application/json')) {
      throw new Error(`Expected JSON, got ${res.status} ${type}: ${(await res.text()).slice(0, 200)}`);
    }
    const data = await res.json();

PHP

  1. Send header('Content-Type: application/json'), echo only json_encode(...), and make sure no whitespace/BOM or warnings are printed before it.

React

  1. Vite: add server: { proxy: { '/api': 'http://localhost:8000' } } so API calls don’t hit index.html.

How to diagnose

  1. Raw body — What does res.text() contain?
  2. Status — Is it a 4xx/5xx/3xx?
  3. URL — Is the path/host correct?
  4. Server output — Any warnings printed before JSON?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.