node parse_error ai_generated true

SyntaxError: Unexpected token < in JSON at position 0

ID: node/json-parse-unexpected-token

Also available as: JSON · Markdown
92%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
20 active

Root Cause

JSON.parse received non-JSON data. Common: API returned HTML error page instead of JSON.

generic

Workarounds

  1. 95% success Log the actual response text to see what was returned (often an HTML error page)
    const text = await res.text();
    console.log(text); // see what the server actually sent

    Sources: https://developer.mozilla.org/en-US/docs/Web/API/Response/text

  2. 92% success Check response status before parsing: if (!res.ok) throw new Error(res.statusText)
    if (!res.ok) throw new Error(res.statusText)

    Sources: https://developer.mozilla.org/en-US/docs/Web/API/Response/ok

  3. 88% success Verify the API URL is correct and the server is returning JSON content-type
    Verify the API URL is correct and the server is returning JSON content-type

    Sources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

Dead Ends

Common approaches that don't work:

  1. Add try/catch and return empty object 70% fail

    Hides the real issue — the response isn't JSON

  2. Strip non-JSON characters from the string 80% fail

    If you're getting HTML, stripping won't make it JSON

Error Chain

Frequently confused with: