How to Fix 'SyntaxError: Unexpected end of JSON input' in Node.js

beginner💚 Node.js2026-05-18| Node.js (All versions), Browser Fetch API, Express.js

Error Message

SyntaxError: Unexpected end of JSON input
#json#parsing#syntax-error#fetch#api

The ContextYou’re staring at your terminal at 2 AM, and a single line keeps mocking you: SyntaxError: Unexpected end of JSON input. This error is a rite of passage in Node.js development. It usually crops up when you are juggling API responses, reading local configuration files, or streaming data between services.

Simply put, this error means JSON.parse() started reading a string and expected more data to finish a valid structure, but the string stopped unexpectedly. It's like a waiter taking your plate away while you're still mid-bite. Usually, the culprit isn't a typo in your JSON—it's that the data is an empty string, undefined, or a truncated network packet.

The Debugging ProcessStop looking for missing commas. When this error hits, the first mistake most developers make is auditing the structure of their JSON. Don't do that yet. Instead, verify the existence of the data.

1. Log the Raw InputBefore you call JSON.parse() or res.json(), inspect the raw data. If you are using the Fetch API, don't jump straight to .json(). Use .text() first to see the literal characters coming over the wire.

// Debugging a fetch call
const response = await fetch('https://api.example.com/data');
const rawText = await response.text();

console.log('Raw output:', rawText);
console.log('Byte length:', rawText.length);

// Only parse if we actually have content
const data = rawText ? JSON.parse(rawText) : {};

If rawText is an empty string (""), JSON.parse() will fail 100% of the time. A 0-byte response is the most common cause of this headache.

2. Check HTTP Status CodesA 204 No Content or a 404 Not Found response often returns a completely empty body. If your logic assumes a successful 200 OK with a valid payload, the code will crash the moment it tries to parse that void.

Common Scenarios and Solutions### Scenario A: The Empty API ResponseMany modern REST APIs return an empty body for DELETE or PUT requests. If your code tries to parse the result of a deletion, it will likely throw an error.

const res = await fetch(url, { method: 'DELETE' });
// This line will crash if the server returns a 204 No Content
const body = await res.json(); 

The Fix: Check the status code or content length before you attempt to parse.

const res = await fetch(url, { method: 'DELETE' });
let data = {};

if (res.status !== 204 && res.ok) {
    data = await res.json();
}

Scenario B: Reading a 0-byte FileUsing fs.readFileSync to load a config file? If that file is empty—perhaps due to a failed write operation earlier—the parser will choke.

const fs = require('fs');
// If config.json is 0 bytes, this throws the error
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));

The Fix: Validate that the string has content before passing it to the parser.

const rawConfig = fs.readFileSync('./config.json', 'utf8');
const config = rawConfig.trim() ? JSON.parse(rawConfig) : {};

Scenario C: Truncated StreamsWhen collecting data chunks from a Node.js stream, you might be parsing the data before the end event fires. Alternatively, the network connection might have dropped mid-transfer, leaving you with half a JSON object like {"user": "admin", "status": .

let body = '';
req.on('data', chunk => {
    body += chunk;
});
req.on('end', () => {
    try {
        const data = JSON.parse(body);
    } catch (e) {
        console.error("Received incomplete JSON. The connection likely dropped.");
    }
});

Verification StepsSimulate a failure to ensure your fix actually works. You can use a tool like Postman to mock a 200 OK response with a 0-byte body. If your application survives this without crashing, you're in good shape.

Write a unit test that passes an empty string and a partial JSON string (like {"id": 1) to your parsing function. It should return a default value or a helpful custom error instead of letting the generic SyntaxError bubble up.

Prevention and Best PracticesAlways wrap JSON.parse() in a try-catch block. JSON is external data, and you should never trust it. It doesn't matter if the API documentation promises a perfect object; the network is unreliable.

If you're dealing with massive payloads that keep failing, try copying the raw output into a validator. I use the JSON Formatter & Validator on ToolCraft. It’s useful for spotting hidden non-printable characters or seeing exactly where a payload was cut off. Because it runs in the browser, you don't risk sending sensitive production logs to a random server.

Lessons Learned- Verify existence first: An empty string is not valid JSON. Always check the string length.- Status codes matter: A 204 or 404 response is a signal that there is likely no data to parse.- Use defaults: Provide a fallback, such as an empty object {}, to prevent your entire service from crashing over a missing response body.

Related Error Notes