ENRU

Unexpected token '<' in JSON: the server sent an HTML page

Updated

You asked for JSON and got a web page. SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON is how V8 (Chrome, Edge, Node.js) reports it: the < it stopped at is the first character of an HTML document. There is nothing to repair in the JSON, because there isn’t any. The question is why the server answered with a page, and the answer is in the response, not in the parser.

Older Node.js and Chrome word it as Unexpected token < in JSON at position 0. Firefox says unexpected character at line 1 column 1, Safari Unrecognized token '<', Python Expecting value: line 1 column 1 (char 0), Go invalid character '<' looking for beginning of value; the full list is below. Position 0, column 1, char 0: the very first character is already wrong, so the body is not damaged JSON but something else entirely.

Read the quoted text: it is the start of the body

Since Node.js 20, V8 quotes the first ten characters of what it was given and adds ... when there was more. That quote is the quickest diagnosis available, before you open any tool:

Quoted startWhat you receivedCheck
"<!DOCTYPE "... or "<!doctype "...A complete HTML page: an error page, a login form or your own app’s index.htmlStatus code and the final URL after redirects
"<html> followed by a line breakAn HTML page without a doctype. The default nginx 502 and 504 pages look like thisStatus code; proxy and backend logs
"<?xml vers"...An <?xml document: an error from a web service or an object storage bucketURL, method and credentials
"<br /> followed by a line breakA PHP warning or notice printed in front of your JSONThe PHP error log; display_errors should be off in production
..."2, "bio": <b>hi</b>}"A < in the middle: the body is JSON with raw HTML inside a valueThe code that builds the JSON; see unexpected character
'I', "Internal S"..., 'N', "Not Found"Plain text instead of HTML. Same story: an error message where the data should beStatus code
"undefined", "[object Object]"No response at all: the wrong value was passed to JSON.parse“undefined” is not valid JSON

An empty body produces a different message, Unexpected end of JSON input, which has its own page.

RFC 8259 defines a JSON text as JSON-text = ws value ws, and a value starts with {, [, ", a digit, -, t, f or n. Nothing starts with <, so every parser that follows the standard stops at the first character.

See the response your code actually got

Don’t debug the parser; look at what came back. Three places to look, quickest first:

  1. DevTools. In the Network tab, click the failing request and open Response. Note the status, the Content-Type response header and any 301 or 302 right before it. Right-click the request and choose Copy as cURL: you get the same request, with the same cookies, for the terminal.
  2. curl. -i prints the status line and headers above the body. -w prints only the fields you ask for and doesn’t follow redirects, so a login redirect shows up as a 302 with its target.
  3. Your code. Log the status, the type, the final URL and the first characters of the body before parsing.
$ curl -sS -i https://example.com/api/users/42
HTTP/2 200
content-type: text/html; charset=utf-8

<!DOCTYPE html>
<html lang="en">

$ curl -sS -o /dev/null -w '%{http_code} %{content_type} %{redirect_url}\n' https://example.com/api/me
302  https://example.com/login?next=/api/me
const res = await fetch('/api/users/42');
const text = await res.text();
console.log(res.status, res.headers.get('content-type'), res.redirected, res.url);
console.log(text.slice(0, 200));

fetch follows redirects without telling you; res.redirected and res.url are how you notice. axios is quieter still: with default settings an HTML body with status 200 doesn’t throw at all, and response.data simply becomes the HTML string (checked on axios 1.21). The error surfaces later, when something calls JSON.parse(response.data) or reads response.data.items and gets undefined. For 4xx and 5xx axios throws Request failed with status code 500, and the HTML is in error.response.data.

Why a server answers a JSON request with HTML

  • 200, text/html, your own app’s page. The request never reached the API. The server of a single-page app answers every unknown path with index.html. Typical triggers: a relative URL (fetch('api/users') on /users/42 requests /users/api/users), a dev server with no proxy to the backend, an unset base URL (${apiBase}/users turns into undefined/users), or a data.json that isn’t where the code expects it.
  • 200 after a redirect. The session expired and the server sent the request to the login page. fetch followed the 302 and handed the login form to JSON.parse.
  • 401 or 403 with HTML. An authentication layer, a firewall or a bot check answered before your API did.
  • 404 with HTML. Wrong path or wrong method. Most frameworks render their default 404 as a page.
  • 500 with HTML. An unhandled exception. The default error handler of Express answers with an HTML page; so do Django and Rails in debug mode.
  • 502, 503 or 504 with HTML. The backend is down or too slow, and the proxy, load balancer or content delivery network in front of it sent its own error page.
  • PHP output before the JSON. With display_errors on, a warning lands in the body ahead of your json_encode output, and the body starts with <br />.

The same error in other engines and languages

Every parser stops at the <; only the wording differs. Each message below was produced by feeding the same HTML page to the parser of the version in the first column. Rows marked “source” come from the engine’s source code, where the engine itself couldn’t be run for the check. Firefox lists its messages in Mozilla’s reference.

Engine, version checkedMessageNote
Chrome 156, Node.js 20.20 and 25.1 (V8)SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSONCurrent wording, also in Edge. The console may add Uncaught (in promise) in front
Node.js 18.20 (V8 10.2)SyntaxError: Unexpected token < in JSON at position 0The older wording, still common in answers and logs
Firefox (source: SpiderMonkey)SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON dataSame from response.json()
Safari, JavaScriptCore of macOS 27.0.1SyntaxError: JSON Parse error: Unrecognized token '<'From JSON.parse; React Native on JavaScriptCore says the same
Safari response.json() (source: WebKit)SyntaxError: The string did not match the expected pattern.A generic WebKit text: no JSON, no <, no position
React Native, Hermes (source)SyntaxError: JSON Parse error: Unexpected character: <Hermes is the default engine of current React Native
Python 3.9.6 and 3.14.10, requests 2.32.5requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)Plain json.loads raises json.decoder.JSONDecodeError with the same text; see Expecting value
Python, aiohttp 3.13.5aiohttp.client_exceptions.ContentTypeError: 200, message='Attempt to decode JSON with unexpected mimetype: text/html; charset=utf-8'Checks Content-Type before parsing; the URL follows the message
Go 1.25.3, encoding/jsoninvalid character '<' looking for beginning of valueSame from json.Unmarshal and json.Decoder
Java, Jackson 2.20.1com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')Followed by line: 1, column: 1
Java, Gson 2.13.2com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $Gson reads <!DOCTYPE as an unquoted string; Retrofit with the Gson converter shows this
C#, System.Text.Json 10 (runtime 10.0.14)System.Text.Json.JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.GetFromJsonAsync and ReadFromJsonAsync don’t check Content-Type. Line and byte count from 0
C#, Newtonsoft.Json 13.0.4Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
PHP 8.5.12Syntax errorjson_decode returns null, json_last_error() is 4; with JSON_THROW_ON_ERROR a JsonException carries the same text
jq 1.7.1 and 1.8.2jq: parse error: Invalid numeric literal at line 1, column 10jq takes <!DOCTYPE for a malformed number and stops at the space after it

Fix: check status and Content-Type before parsing

The parser is the wrong place to learn that a request failed. Check the status and the Content-Type first, and put the start of the body into the error, so the next report reads “502 text/html: <html>…” instead of “Unexpected token”. Each snippet below was run against a test server answering with JSON, an HTML page, an HTML 500 and an empty 204.

JavaScript (fetch)

async function getJson(url, options) {
  const res = await fetch(url, options);
  const type = res.headers.get('content-type') ?? '';
  const text = await res.text();
  if (res.ok && type.includes('json')) return JSON.parse(text);
  throw new Error(`${res.status} ${type} from ${res.url}: ${text.slice(0, 200)}`);
}

Python (requests)

import requests

def get_json(url, **kwargs):
    r = requests.get(url, timeout=10, **kwargs)
    ctype = r.headers.get("Content-Type", "")
    if r.ok and "json" in ctype:
        return r.json()
    raise RuntimeError(f"{r.status_code} {ctype} from {r.url}: {repr(r.text[:200])}")

Go

func getJSON(url string, v any) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	ct := resp.Header.Get("Content-Type")
	if resp.StatusCode >= 300 || !strings.Contains(ct, "json") {
		return fmt.Errorf("%s %s: %.200q", resp.Status, ct, body)
	}
	return json.Unmarshal(body, v)
}

Java (HttpClient and Jackson)

static JsonNode getJson(String url) throws IOException, InterruptedException {
    HttpResponse<String> resp = http.send(
        HttpRequest.newBuilder(URI.create(url)).build(),
        HttpResponse.BodyHandlers.ofString());
    String type = resp.headers().firstValue("Content-Type").orElse("");
    String body = resp.body();
    if (resp.statusCode() >= 300 || !type.contains("json")) {
        throw new IOException(resp.statusCode() + " " + type + ": "
            + body.substring(0, Math.min(body.length(), 200)));
    }
    return mapper.readTree(body);
}

C# (HttpClient)

static async Task<T?> GetJson<T>(HttpClient http, string url)
{
    using var resp = await http.GetAsync(url);
    var type = resp.Content.Headers.ContentType?.MediaType ?? "";
    var body = await resp.Content.ReadAsStringAsync();
    if (resp.IsSuccessStatusCode && type.Contains("json"))
        return JsonSerializer.Deserialize<T>(body);
    throw new HttpRequestException($"{(int)resp.StatusCode} {type}: {body[..Math.Min(body.Length, 200)]}");
}

PHP (curl)

function getJson(string $url): array
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    if ($status >= 300 || strpos($type, 'json') === false) {
        throw new RuntimeException("$status $type: " . substr($body, 0, 200));
    }
    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

The type check looks for json anywhere in the header instead of an exact application/json, so a charset parameter or a type like application/problem+json (the error format of RFC 9457) still passes.

Keep it from coming back

Keep the app fallback away from the API. In nginx, give /api/ its own location before the catch-all try_files, so a wrong API path reaches the backend and gets its 404 instead of index.html:

location /api/ {
    proxy_pass http://backend;
}

location / {
    try_files $uri $uri/ /index.html;
}

In development, proxy API calls through the dev server rather than letting it serve the app for every path. Vite shown; other dev servers have the same option:

// vite.config.js
export default {
  server: {
    proxy: { '/api': 'http://localhost:8080' },
  },
};
  • Make the API answer errors in JSON. A catch-all error handler that sets Content-Type: application/json for 404 and 500 turns this message into a readable one.
  • Ask for JSON. Send Accept: application/json. Some frameworks, Laravel among them, then return 401 and validation errors as JSON instead of redirecting to a login page.
  • One base URL, checked at startup. Use absolute paths such as /api/users or a single configured base, and stop at startup when it is empty.
  • One helper for every call. A getJson like the one above makes the status check impossible to forget, and its error already contains the diagnosis.

Try it

Paste the start of the body into the validator: it stops at line 1, column 1 and names the character. A position from a longer message, such as at position 1234 or char 1234, becomes a line and column in the position finder.

Related: Unexpected end of JSON input for empty bodies, Expecting value for the Python side, unexpected character for a stray character inside real JSON, and the list of JSON errors.

Unexpected token in JSON FAQ

What does the “Unexpected token” error mean?

The first character of what you parsed is <, so the text is HTML or other markup, not JSON. The request returned a web page (an error page, a login form or your app’s index.html) and the code tried to read it as data.

Why does it say “position 0”?

Position 0 is the first character. Node.js 18 and older say Unexpected token < in JSON at position 0; Node.js 20 and current Chrome quote the start of the body instead, as in "<!DOCTYPE "....

It works in the browser but fails in my script. Why?

The browser sends cookies and a session; a script usually doesn’t, so it is redirected to a login page or stopped by a bot check, and parses that page. Copy the browser’s request as cURL in DevTools and compare the headers.

Can I make the parser accept the HTML?

No, and there would be nothing to gain: the data isn’t in that page. Fix the URL, the session or the server, and make the client report the status and Content-Type whenever the body isn’t JSON.