Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Web

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

· 9 min read

You load some data with fetch, and instead of your data the console shows:

Console
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Unexpected token '<', "<!DOCTYPE "... is not valid JSON means your code asked for JSON data, but what came back was an HTML page. HTML pages start with <!DOCTYPE html>, and the very first character, <, can't start valid JSON, so the parser stops there. The message even quotes the start of what it received: "<!DOCTYPE ". Most of the time that HTML page is a 404 "Not found" page, because the URL in your fetch is wrong. This article shows how to see exactly what came back and fix each common cause.

Try it yourself

This happens with any fetch to a URL that doesn't exist on your server. For example, in a page served by a local server:

app.js
async function load() {
  const response = await fetch("/data/scores.json");
  const data = await response.json();
  console.log(data);
}
load();

If /data/scores.json doesn't exist, the console shows two lines:

Console
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

The first line is the real problem. The second is what happens next, when response.json() tries to read the 404 page as JSON.

What the error means

Read it in parts:

  • Uncaught (in promise): the error happened inside asynchronous code (fetch and .json() return promises) and nothing caught it.
  • SyntaxError: the text couldn't be read as JSON. It's about the data, not your JavaScript.
  • Unexpected token '<': the first character that didn't fit. JSON must start with {, [, a quote, a number, true, false or null.
  • "<!DOCTYPE "...: the beginning of the text that was received. This is your biggest clue.
  • is not valid JSON: so JSON.parse (which response.json() uses) gave up.

So the question is: why did the server send an HTML page instead of JSON?

Step 1: look at what came back

Before changing anything, see the response. Replace .json() with .text() for a moment, and log the status:

js
const response = await fetch("/data/scores.json");
console.log(response.status, response.ok, response.headers.get("content-type"));
const text = await response.text();
console.log(text.slice(0, 40));
Console
404 false text/html
<!DOCTYPE html><html><head><title>404</t

Now you know: status 404, the server sent HTML, and it's a "not found" page. You can see the same in the browser's Network tab: click the request, then look at the status and the Response tab.

Cause 1: the wrong URL or path (404)

The most common cause. The file isn't where the fetch URL points. Check:

  • The folder. fetch("/data/scores.json") looks in a data folder at the root of the site. fetch("data/scores.json"), without the leading /, looks relative to the current page. These are different places when the page is in a subfolder.
  • The file name and capitals. On many servers, Scores.json and scores.json are different files.
  • The API path. For an API, check the exact route in its documentation: /api/users versus /api/user, or a missing version like /v1/.

A quick check: paste the full URL from the error into the browser's address bar. If you see a "not found" page instead of your data, the URL is wrong.

Cause 2: a single-page app that answers every URL with index.html

Some development servers and hosting setups for single-page apps send index.html for any URL they don't recognise, with status 200, so the app's router can handle it. Then a wrong data URL doesn't give a 404: it gives your own home page, and the same "<!DOCTYPE " error.

The .text() check from step 1 shows it: the HTML will be your own page's HTML. The fix is the same as cause 1: correct the URL, and make sure the data file is in the folder your server publishes (often called public).

Cause 3: a server error page

If the URL is right but the server fails, it may answer with an HTML error page, status 500. The .text() check will show something like an "Internal Server Error" page. The fix is on the server side: look at the server's own log. Your fetch code is fine.

Cause 4: a login page

When an API needs you to be signed in and you're not, some servers redirect to a login page, which is HTML. The status after the redirect may even be 200. Look at the HTML text: if it contains a login form, the request needs authentication.

Cause 5: opening the file directly, without a server

If you open index.html by double-clicking it, the address bar starts with file://. Browsers block fetch to local files in that case, and you'll see a different error about the request being blocked. Run a small local server instead, for example the Live Server extension in VS Code, or npx serve in the project folder, and open the page through http://localhost.

The fix in code: check response.ok first

Whatever the cause, your code should check the status before parsing. response.ok is true for status 200 to 299:

js
async function load() {
  const response = await fetch("/data/scores.json");
  if (!response.ok) {
    throw new Error("HTTP " + response.status + " for " + response.url);
  }
  return response.json();
}
load().catch(e => console.log("caught:", e.message));
Console
Failed to load resource: the server responded with a status of 404 (Not Found)
caught: HTTP 404 for http://localhost:8767/data/scores.json

Now the error says exactly what went wrong and which URL failed, instead of a confusing JSON message. With the right URL, the same code returned the data: in our test, {"scores":[72,85,90]} became an object, and data.scores printed [72, 85, 90].

Other "is not valid JSON" messages

The same family of errors appears whenever JSON.parse gets text that isn't JSON. In our tests with Chromium:

Console
"undefined" is not valid JSON
Unexpected end of JSON input
Unexpected token 'H', "Hello" is not valid JSON
Expected property name or '}' in JSON at position 1 (line 1 column 2)
Expected double-quoted property name in JSON at position 8 (line 1 column 9)
"[object Object]" is not valid JSON

What each one means:

  • "undefined" is not valid JSON: you passed undefined: a variable that was never set, or a property that doesn't exist, like data.reponse with a typo.
  • Unexpected end of JSON input: the text was empty. With fetch, the full message is Failed to execute 'json' on 'Response': Unexpected end of JSON input: the server answered with an empty body.
  • Unexpected token 'H', "Hello": the server sent plain text. The quoted part shows it.
  • Expected property name or '}': single quotes, like {'name': 'Sam'}. JSON requires double quotes.
  • Expected double-quoted property name ... at position 8: a trailing comma, like {"a": 1,}. JSON doesn't allow it.
  • "[object Object]" is not valid JSON: you passed an object, not text, to JSON.parse. It's already parsed: use it directly.

Older wording and other browsers

Older versions of Chrome and Node.js worded the first error as:

Console
SyntaxError: Unexpected token < in JSON at position 0

Same error, same causes. Firefox says something like JSON.parse: unexpected character at line 1 column 1 of the JSON data. In every version, "unexpected character at the first position" combined with < means HTML.

Errors that look alike

  • x.forEach is not a function after loading data: the data arrived but isn't an array, often because it's still text or the array is inside an object. See forEach is not a function.
  • CORS errors ("blocked by CORS policy"): the browser refused to give you the response at all, because the server didn't allow your site. That's a server setting, not a JSON problem.
  • Cannot set properties of null: an element wasn't found when you tried to show the data. See Cannot set properties of null (setting 'innerHTML').

Wrong fixes that don't help

  • Wrapping JSON.parse in try/catch and ignoring the error. Your data still didn't arrive.
  • Changing .json() to .text() permanently. You'd get the HTML 404 page as your "data".
  • Adding "Content-Type": "application/json" to the request. That header describes what you send, not what the server sends back. It doesn't make a 404 page into JSON.

A debugging walkthrough

  1. Look for a red 404 or 500 line just above the JSON error in the console.
  2. Open the Network tab, reload, and click the request. Check the status and the URL that was actually requested.
  3. Open that URL in a new tab. Do you see your data, or an HTML page?
  4. Fix the URL (folder, leading /, capitals, API route), or the server if it's a 500.
  5. Add the response.ok check, so the next time a URL is wrong, the message says so directly.

Practice

What does JSON.parse say for each?

  1. JSON.parse("")
  2. JSON.parse("{'a': 1}")
  3. JSON.parse('{"a": 1}')

Answers. (1) Unexpected end of JSON input: empty text. (2) Expected property name or '}' in JSON at position 1: single quotes aren't JSON. (3) Works: gives the object { a: 1 }.

Frequently asked questions

What does "Unexpected token '<'" mean in JSON?

The text started with <, which means it was HTML, not JSON. Usually it's an error page.

Why does fetch return HTML instead of JSON?

Most often, the URL is wrong and the server sent its 404 page. It can also be a server error page, a login page, or a single-page app returning index.html.

How do I see what fetch actually returned?

Use await response.text() and log it, or open the request in the browser's Network tab.

Does response.json() check the status code?

No. It tries to parse whatever the body is, even a 404 page. Check response.ok first.

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

Yes. That's the older wording of the same error.

A quick checklist

  1. Look for a 404 or 500 line above the error.
  2. Log response.status and await response.text().
  3. Open the URL in a new tab.
  4. Fix the path: folder, leading /, file name capitals.
  5. Check response.ok before calling response.json().

For a method that works on any error, read how to read an error message. MDN documents Using the Fetch API and JSON.parse.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right