Skip to main content
btheo.com btheo.com > press start to play
NEW POST: NODE.JS SECURITY 2025 OPEN FOR FREELANCE 10+ YEARS EXP REACT × NODE × AWS NEW POST: NODE.JS SECURITY 2025 OPEN FOR FREELANCE 10+ YEARS EXP REACT × NODE × AWS
TIL · 01 APR 2026 · NOTE #026 ESC
TIL NOTE #026

JSON.parse Throws — Always Wrap It

The problem:

const data = JSON.parse(userInput); // Crashes if invalid

User sends malformed JSON. App crashes. Error log floods. Restart loop.

The fix:

function parseJSON<T>(input: string, fallback: T): T {
try {
return JSON.parse(input);
} catch {
console.error("Invalid JSON:", input);
return fallback;
}
}
const data = parseJSON(userInput, {});

Or zod for validation:

const data = z.string().pipe(z.string().transform(JSON.parse)).parse(userInput);

Never trust external data. From the user, from an API, from a file. Always validate. Parse defensively.

Untrusted input is the root cause of 80% of production incidents. JSON.parse is just one vector.