@FahadM to JavaScriptEnglish • 5 days ago

Why does JSON.parse throw ""SyntaxError: Unexpected token < in JSON at position 0""?

message-square
0
1
Why does JSON.parse throw ""SyntaxError: Unexpected token < in JSON at position 0""?
@FahadM to JavaScriptEnglish • 5 days ago

JSON.parse throws SyntaxError: Unexpected token < in JSON at position 0 because the string passed to JSON.parse() (or response.json()) starts with <—almost always HTML (such as <!DOCTYPE html>, <html>, or an error/login/404 page) or XML rather than valid JSON ({...}, [...], "...", 123, true, null). In web apps, this happens most often when a fetch() or AJAX call hits a wrong endpoint, a 404/500 server error page, a login/auth redirect HTML page, or an SPA fallback (index.html) served for an unknown /api/... route.


1. Diagnosing and Guarding JSON.parse() Against Non-JSON (HTML/XML) Payloads

Inspect the raw response text and Content-Type header before calling JSON.parse() so you can surface clear diagnostics and never mutate incoming strings or objects:

// Safely parse a JSON string while guarding against empty or HTML/XML responses
function safeParseJsonString(rawText, { fallback = null } = {}) {
  if (typeof rawText !== "string") {
    throw new TypeError("Expected a string input for JSON.parse().");
  }

  const trimmed = rawText.trim();
  if (trimmed === "") {
    throw new SyntaxError("Cannot parse empty string as JSON.");
  }

  if (trimmed.startsWith("<")) {
    const preview = trimmed.slice(0, 120).replace(/\s+/g, " ");
    throw new SyntaxError(
      `Expected JSON, but received markup starting with "<" (likely HTML/XML): "${preview}"`
    );
  }

  try {
    return JSON.parse(trimmed);
  } catch (err) {
    if (fallback !== undefined && fallback !== null) {
      return fallback;
    }
    throw err;
  }
}

// Example usage:
// console.log(safeParseJsonString('{"ok":true}')); // { ok: true }
  • Catches < early: Identifies HTML (<!doctype html>, <html>) or XML immediately instead of failing obscurely at index 0.
  • Non-mutating: Reads rawText without altering strings or caller state.

2. Checking response.ok and Content-Type Before Parsing fetch() Responses

In fetch() workflows, check response.ok and read await response.text() first so a 404 HTML error page or 302 HTML login page can be inspected cleanly instead of crashing inside response.json() or JSON.parse():

// Fetch an endpoint and parse JSON only when status is OK and content is JSON-compatible
async function fetchJsonWithDiagnostics(url, options = {}) {
  if (typeof url !== "string" || url.trim() === "") {
    throw new TypeError("Expected a valid endpoint URL.");
  }

  const safeOptions = {
    ...options,
    headers: {
      Accept: "application/json",
      ...(options && typeof options.headers === "object" ? options.headers : {})
    }
  };

  const response = await fetch(url, safeOptions);
  const rawBody = await response.text();
  const contentType = (response.headers.get("content-type") || "").toLowerCase();

  if (!response.ok) {
    throw new Error(
      `Request to "${url}" failed with HTTP ${response.status} (${response.statusText}). Body preview: ${rawBody.slice(0, 120)}`
    );
  }

  if (rawBody.trim().startsWith("<") || (!contentType.includes("json") && rawBody.trim().startsWith("<"))) {
    throw new SyntaxError(
      `Expected JSON from "${url}" (content-type: "${contentType || "none"}"), but received HTML/XML starting with "<".`
    );
  }

  return JSON.parse(rawBody);
}

// Example usage:
// fetchJsonWithDiagnostics("/api/users")
//   .then((users) => console.log(users))
//   .catch((err) => console.error(err.message));
  • Reads response.text() once: Avoids double-reading stream errors while letting you inspect both HTTP status and the first characters of the body.
  • Surfaces exact endpoint/HTTP context: Helps pinpoint wrong API URLs, missing server routes, or auth redirects fast.

3. Common Traps to Avoid

"SyntaxError: Unexpected token < in JSON at position 0" frequently stems from a few recurring causes:

  • Wrong API URL or SPA fallback returning index.html: Requesting /api/data on a static or SPA server that rewrites unmatched paths to index.html returns HTML starting with <!doctype html>.
  • Server-side 404, 500, or PHP/framework error page returning HTML: An unhandled backend error or PHP fatal/warning page often sends HTML instead of JSON with Content-Type: application/json.
  • Session expiration redirecting to an HTML login page: Unauthenticated API calls sometimes respond with 200 or 302 containing an HTML sign-in form starting with <.

TL;DR: JSON.parse throws SyntaxError: Unexpected token < in JSON at position 0 when given HTML or XML starting with < instead of valid JSON—verify response.ok, check the endpoint URL/auth/server error response, and inspect the raw text before parsing.