SyntaxError: Unexpected end of JSON input
JSON.parse() received an empty string, incomplete JSON, or something that isn’t JSON at all.
Fix 1: Check for empty responses
// ❌ API returned empty body
const response = await fetch('/api/data');
const data = await response.json(); // Crashes if body is empty!
// ✅ Check first
const response = await fetch('/api/data');
const text = await response.text();
const data = text ? JSON.parse(text) : null;
Fix 2: Check the response status
const response = await fetch('/api/data');
// ❌ Don't parse error responses as JSON
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
A 204 (No Content) or 500 response often has no body.
Fix 3: The response isn’t JSON
Your API might be returning HTML (like a 404 page) instead of JSON:
const response = await fetch('/api/data');
const text = await response.text();
console.log(text); // Check what you actually got
// If it starts with "<" it's HTML, not JSON
if (text.startsWith('<')) {
throw new Error('Got HTML instead of JSON — check your API URL');
}
const data = JSON.parse(text);
Fix 4: localStorage returning null
// ❌ localStorage.getItem returns null if key doesn't exist
const data = JSON.parse(localStorage.getItem('settings')); // Crashes!
// ✅ Provide a default
const data = JSON.parse(localStorage.getItem('settings') || '{}');
Fix 5: Truncated JSON string
If you’re building JSON manually or receiving it from a stream:
// ❌ Incomplete JSON
const broken = '{"name": "Alice", "age":';
JSON.parse(broken); // Unexpected end of JSON input
// ✅ Always validate
try {
const data = JSON.parse(jsonString);
} catch (e) {
console.error('Invalid JSON:', jsonString.slice(0, 100));
}