Common causes
1. Parsing a variable that was never set
A missing environment variable, request field or object property is undefined, and JSON.parse(undefined) throws this exact error. Check for the value first or fall back to a default.
const settings = JSON.parse(process.env.APP_SETTINGS);const raw = process.env.APP_SETTINGS;
const settings = raw === undefined ? {} : JSON.parse(raw);2. Storing undefined in localStorage
JSON.stringify(undefined) returns undefined, and localStorage.setItem stores it as the text “undefined”. Reading it back later fails. Note that a missing key returns null, which JSON.parse accepts.
localStorage.setItem('cart', JSON.stringify(cart));
const saved = JSON.parse(localStorage.getItem('cart'));if (cart !== undefined) localStorage.setItem('cart', JSON.stringify(cart));
const saved = JSON.parse(localStorage.getItem('cart') ?? 'null');3. Building JSON with string concatenation
Concatenating values into a JSON string writes the word undefined whenever a value is missing. JSON.stringify builds the text correctly: it omits undefined properties and turns undefined array items into null.
const body = '{"userId": ' + user.id + ', "sessionToken": ' + token + '}';const body = JSON.stringify({ userId: user.id, sessionToken: token });4. The word undefined inside a JSON document
JSON has no undefined value. Use null for “no value”, or leave the property out entirely. Fix it in PasteKit replaces undefined with null.
{"userId": 7, "sessionToken": undefined}{"userId": 7, "sessionToken": null}Frequently asked questions
Why does JSON.parse(null) work but JSON.parse(undefined) fail?
Both are converted to strings first. null becomes “null”, which is valid JSON, while undefined becomes “undefined”, which is not. That is why a missing localStorage key (null) parses fine but a missing variable (undefined) throws.
Does JSON support undefined?
No. JSON values are objects, arrays, strings, numbers, true, false and null. JSON.stringify drops object properties whose value is undefined and writes null for undefined array items.
How do I find which value is undefined?
Log the argument with typeof right before the parse call. If it is the string “undefined”, look at where it was saved; if it is the value undefined, the variable or property was never set.