Quick answer

JSON.parse(undefined) converts undefined to the text undefined, which is not valid JSON. The parser stops at the letter u. Fix: find out why the value is undefined (a missing property, a function that returns nothing, a bad localStorage value) and check it before parsing.

The same error in different browsers

Example that fails

const config = {};
JSON.parse(config.data);   // config.data is undefined

Common causes

1. A missing property or wrong key name

You read response.data, body.payload or event.detail, but the property does not exist or has a different name. Print the whole object to check.

2. A function that returns nothing

A function without a return statement gives undefined. Passing its result to JSON.parse() fails.

3. The text "undefined" saved in localStorage

JSON.stringify(undefined) returns undefined, and localStorage.setItem("key", undefined) stores the text "undefined". Later, getItem returns that text, and parsing it fails.

// bad: stores the text "undefined" if value is undefined
localStorage.setItem("prefs", JSON.stringify(value));

// better: only save real values
if (value !== undefined) {
  localStorage.setItem("prefs", JSON.stringify(value));
}

If the bad text is already saved, run localStorage.removeItem("prefs") once to clear it.

A safe parse helper

function safeParse(text, fallback = null) {
  if (typeof text !== "string") return fallback;
  try {
    return JSON.parse(text);
  } catch (e) {
    return fallback;
  }
}

const prefs = safeParse(localStorage.getItem("prefs"), {});

If you have a string with JSON in it

Paste it into the JSON Formatter to check the syntax. Broken text can be fixed with the JSON Repair tool.

Have broken JSON right now?

Paste it into the free JSON Repair tool. It runs in your browser, so nothing is uploaded.

Open JSON Repair tool

FAQ

Is undefined valid in JSON?

No. JSON has no undefined value. It supports strings, numbers, booleans, null, arrays and objects. When JSON.stringify meets an undefined property in an object, it leaves that property out.

What is the difference between null and undefined here?

JSON.parse(null) returns null without an error, but JSON.parse(undefined) throws.

Why does it only fail on the first page load?

On the first visit nothing is saved yet, so the value is missing. Always give your code a fallback for that case.

Related guides