TIL NOTE #026
JSON.parse Throws — Always Wrap It
The problem:
const data = JSON.parse(userInput); // Crashes if invalidUser 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.