← Back to Error Lab

SyntaxError: Unexpected token < in JSON at position 0

Published 2026-04-12

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

This error occurs when you use `JSON.parse()` on a string that is not valid JSON. The "<" symbol is a dead giveaway: it means you are trying to parse HTML as JSON. This almost always happens when an API request fails, and the server returns a 404 (Not Found) or 500 (Internal Server Error) HTML error page instead of the expected JSON payload. When your frontend code blindly calls `response.json()` without checking the response status or content type, it chokes on the HTML response.

Fix / Solution

Always verify the HTTP response status (`response.ok`) and the `Content-Type` header before attempting to parse the body as JSON. Implement proper error handling to catch non-200 responses and gracefully inform the user or retry the request, rather than letting the JSON parser crash the application.

Code Snippet

// ❌ Blindly parsing without checking
const res = await fetch('/api/data');
const data = await res.json(); // Crashes if /api/data returns HTML

// ✅ Safe parsing with checks
const res = await fetch('/api/data');
if (!res.ok) {
  throw new Error(`API Error: ${res.status}`);
}
const contentType = res.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
  const data = await res.json();
}