"undefined" is not valid JSON: Every Cause and Fix

Published 19 Oct 2026 · 8 min read

JSON.parse() converts whatever you hand it into a string before it parses. JavaScript's undefined becomes the nine letters undefined, and JSON has no such value (it has null, but nothing for "missing"), so the parser fails on the first character. Every cause below is the same story: the data you wanted never existed, and the error is just the first place that fact became visible. Five ways it happens, each reproduced live, plus the guard worth keeping.

Quick answer: the value you passed to JSON.parse() is undefined, or is the literal text "undefined" that something saved earlier. Don't catch the error yet. Log typeof value and the value itself one line before the parse, then trace it back to whatever should have produced it.

Same bug, four spellings

The wording depends on the engine, and on its age. The first row was reproduced on Node.js 22 (V8) while writing this; the rest are the messages these engines produce for the same input.

EngineMessage for JSON.parse(undefined)
Chrome, Edge, Node.js (current V8)"undefined" is not valid JSON
Chrome, Node.js (older V8)Unexpected token u in JSON at position 0
FirefoxJSON.parse: unexpected character at line 1 column 1 of the JSON data
SafariJSON Parse error: Unexpected identifier "undefined"

If your console shows the Firefox form, this walkthrough of that message covers its other causes too.

Quick reference

SymptomMost likely causeFix
Parsing a field from an API responseThe property is missing or misspelled, so the read returned undefinedCheck the real response shape; use optional chaining and handle absence explicitly
Reading a saved preference or sessionAn earlier write stored the text undefinedFix the write; never setItem() a value you haven't stringified and checked
Fails on server start or in CI onlyAn environment variable isn't setValidate config at startup with a clear message
Fails on first render, works after reloadState hasn't loaded yetParse after the data arrives, not during the first render
Stored data contains the word undefined in a text column or cookieA template literal or String() turned a missing value into textValidate before writing; clean the bad rows

1. Reading a property that doesn't exist

The most common trigger. An API returns a field under a different name than you assumed, or omits it when it's empty, and the read quietly gives you undefined. JavaScript doesn't complain about a missing property, so the first sign of trouble is the next function down.

const res = await fetch('/api/settings').then(r => r.json());
const prefs = JSON.parse(res.preferences);   // the API calls it "prefs"
// SyntaxError: "undefined" is not valid JSON

Two fixes, in this order. First confirm the real shape of the response (paste it into JSON Lab and read the keys). Second, decide what absence means: a default, or a real error. And check whether res.preferences is already an object, in which case the parse is redundant; that's the opposite mistake, covered in "[object Object]" is not valid JSON.

See it fail live

This is exactly the text JSON.parse() sees when the property is missing:

Open this example in JSON Lab

2. localStorage that stored the word "undefined"

One detail first, because many guides get it wrong: reading a key that was never written does not throw. getItem() returns null, and JSON.parse(null) is valid: it returns null (verified on Node 22). The error only appears when the key exists and holds the literal text undefined. That happens because setItem() coerces its value to a string, and JSON.stringify(undefined) returns undefined, not a string.

const theme = settings.theme;                         // undefined: user never chose one
localStorage.setItem('theme', JSON.stringify(theme)); // stringify(undefined) -> undefined
// storage now holds the 9-character string "undefined"

// next page load:
JSON.parse(localStorage.getItem('theme'));
// SyntaxError: "undefined" is not valid JSON

The bug is in the write. Skip the save when the value is undefined (removeItem() instead), and treat the read defensively because stale bad values from an older release stay in users' browsers indefinitely:

function readJSON(key, fallback) {
  const raw = localStorage.getItem(key);
  if (raw === null || raw === 'undefined') return fallback;
  try { return JSON.parse(raw); } catch { return fallback; }
}

This is the one place a try/catch is justified: storage is an input you don't control across versions.

See it fail live

The exact value a poisoned key hands back, a real string with nothing parseable in it:

Open this example in JSON Lab

3. An environment variable that isn't set

process.env.SOME_VAR is undefined when the variable doesn't exist. Config blobs passed through the environment, such as service-account credentials or feature-flag maps, are often parsed right at startup, so the failure shows up as a crash in a deploy or CI job that works on your machine.

const creds = JSON.parse(process.env.SERVICE_ACCOUNT);
// SyntaxError: "undefined" is not valid JSON   (only in the environment missing the var)

The error message doesn't name the variable, which is why this one wastes an afternoon. Fail loudly at the boundary instead:

const raw = process.env.SERVICE_ACCOUNT;
if (!raw) throw new Error('SERVICE_ACCOUNT is not set');
const creds = JSON.parse(raw);

See it fail live

What the deploy log is really reporting. The missing variable, reduced to its text:

Open this example in JSON Lab

4. Parsing before the data has loaded

In a component, useState() with no initial value starts as undefined. If the same render parses that value, the first pass throws, even though the second pass, after the fetch resolves, would have been fine. It often looks like "works after a reload" because cached data is available immediately the second time.

const [raw, setRaw] = useState();                 // undefined until the fetch finishes
const config = JSON.parse(raw);                   // runs on the very first render
// SyntaxError: "undefined" is not valid JSON

Don't parse during render. Parse where the data arrives (inside the fetch handler), or derive the value only when raw is defined. The state should hold the parsed result, not the text.

5. A template literal that turned "missing" into text

String building converts undefined silently: `${x}`, '' + x and String(x) all produce the text undefined with no error. Anything written that way (a cookie, a database text column, a CSV cell, a query string) now contains the word, and a later JSON.parse() on it fails, possibly days after the bad write and in a different service.

document.cookie = `profile=${user.profile}`;      // user.profile was undefined
// cookie now says profile=undefined

JSON.parse(readCookie('profile'));
// SyntaxError: "undefined" is not valid JSON

Fix the writer, then clean up what it already wrote; a one-off query for rows or keys equal to 'undefined' finds them. Related trap: JSON.stringify({ a: undefined, b: 1 }) silently drops a ({"b":1}), and inside an array becomes null ([undefined] gives [null]). Both verified on Node 22. If your pipeline needs to tell "unset" from "explicitly empty", use null on purpose.

See it fail live

Paste the shape of an object you suspect got a missing field. JSON Lab will point at the bad undefined token:

Open this example in JSON Lab

Debugging checklist

  1. Log typeof value and JSON.stringify(value) immediately before the failing parse. undefined and the string "undefined" look identical in many consoles; typeof tells them apart.
  2. If it's a real undefined, trace the read: misspelled key, absent field, unset variable, or state that hasn't loaded.
  3. If it's the string "undefined", trace the write: look for setItem() or a template literal that was handed a missing value.
  4. Remember null is fine: JSON.parse(null) returns null. If you see the error, the value is not null.
  5. Fix the source. Add a guard only at boundaries you don't control (storage, cookies, third-party payloads).

Related failures that look similar but aren't: unexpected end of JSON input means the string exists but is empty or cut off, and Unexpected token in JSON covers the broader family of bad first characters, including an HTML error page where JSON was expected.

Frequently asked questions

Why does JSON.parse() say "undefined" is not valid JSON?

JSON.parse() converts its argument to a string before parsing it. A JavaScript undefined becomes the nine-character text undefined, which is not a JSON value (JSON has null, but no undefined), so the parser rejects it at the first character. Either you passed a real undefined, or something earlier saved the text "undefined" and you read it back.

Is this the same as "Unexpected token u in JSON at position 0"?

Yes. Older versions of V8 (Chrome, Node.js) reported the same failure as Unexpected token u in JSON at position 0, naming the first letter of undefined. Current V8 quotes the whole value instead. Firefox says unexpected character at line 1 column 1, and Safari says Unexpected identifier "undefined". Same cause, different wording.

Why doesn't JSON.parse(localStorage.getItem('missing')) throw?

Because getItem() returns null for a key that doesn't exist, and JSON.parse(null) coerces null to the string null, which is valid JSON and parses to null. The error only appears when the key exists and holds the literal text undefined, which is what setItem() stores if you hand it an undefined value.

Should I wrap JSON.parse() in try/catch to fix it?

A try/catch stops the crash but hides the bug: the value you wanted never existed. Fix the source (the missing property, the unset variable, the write that stored undefined) and add a guard only at boundaries you don't control, such as storage that may hold stale data from an older version of your app.

📋 Paste it and see exactly where it breaks

JSON Lab formats, validates, and repairs JSON entirely in your browser. Nothing you paste is uploaded anywhere.

Open JSON Lab →

← Back to Blog · See also: Unexpected Token in JSON →