Square CloudSquare Cloud

Unexpected token < in JSON: your API returned HTML

The error appears when your code parses an HTML response as JSON: the < is the first character of <!DOCTYPE html>. Check the response URL, status and Content-Type before calling res.json().

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Recognize the error message in Chrome, Firefox, Safari and Node.js
  • Find out why the API returned HTML, from the most common cause to the least
  • Diagnose with the Network tab and curl, and fix it on the client and the server
On this page

Your frontend calls the API and, instead of data, the console shows this:

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

The problem isn't the JSON. It's what arrived: the server answered with an HTML page, and your code tried to read that page as JSON. The < is the first character of <!DOCTYPE html>. The question that fixes the error is a different one: why did the API return HTML?

What does the message say in each environment?#

The wording depends on the JavaScript engine, but the error is the same:

text
Chrome, Edge and Node.js (V8):
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

V8, older form:
SyntaxError: Unexpected token < in JSON at position 0

Firefox:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Safari, from JSON.parse():
SyntaxError: JSON Parse error: Unrecognized token '<'

Safari, from res.json():
SyntaxError: The string did not match the expected pattern.

V8's older form still shows up in many searches and in outdated runtimes. Safari's res.json() message doesn't even mention the <, but the cause is the same. Two variations point to it too:

  • Unexpected token 'N', "Not Found" is not valid JSON: the body was plain text, not HTML.
  • Unexpected end of JSON input: the body was empty.

In Python, json.loads() and the requests library's .json() show Expecting value: line 1 column 1 (char 0). With fetch, MDN documents that res.json() rejects with a SyntaxError when the body can't be parsed as JSON. The error only shows up at parse time, after the wrong response has already arrived.

Why did the API return HTML?#

From the most common cause to the least:

Cause Sign in the response Fix
SPA fallback Status 200, text/html, your own app's HTML /api routes before the fallback, or the API's full URL
Error page 404, 500, 502 or 504 with an HTML body Fix the route or the crash, and answer errors in JSON
Redirect to login res.redirected true, res.url ending in /login The API answers a JSON 401
Dev proxy Works on your machine, breaks in production The API's full URL, or one server for both
Empty build variable undefined/ in the URL path Set the variable before the build

1. The URL fell through to a SPA's index.html#

A SPA in production needs a fallback: every path that isn't a file gets index.html, so the browser's router can take over (see 404 on refresh in a SPA). That fallback can't tell a screen from an API call. If /api/users doesn't exist on the server that serves the frontend, it answers with index.html and status 200.

The variations are many: a typo (/api/user instead of /api/users), a missing prefix, or a relative path without a leading slash. fetch("api/users") on a page at /account/settings becomes /account/api/users. Since the status is 200, res.ok is true and nothing warns you before parsing.

2. A 404 or 500 with an error page#

The route doesn't exist or crashed, and the framework answered with its default error page, which is HTML. Express without its own handler returns a 404 with <!DOCTYPE html> and the text Cannot GET /api/x. Proxies and load balancers in front of the app also tend to answer 502 or 504 with their own HTML page when the app is down or slow. 500, 502, 503 and 504 errors explains each code.

3. A redirect to the login page#

The session expired, and the server redirects (302) to /login. fetch follows redirects by default, so your code receives the login page with status 200. The tell is res.redirected being true and res.url ending in /login.

4. The dev proxy doesn't exist in production#

Vite's server.proxy configures the dev server, not the build. On your machine, /api goes to localhost:3000; in production, the same relative URL hits the server that serves the frontend. The reverse happens too: a dev proxy with the wrong prefix lets the request fall through to Vite's own index.html. It is a classic case of works locally, breaks after deploy.

5. The API URL variable was empty at build time#

With fetch(import.meta.env.VITE_API_URL + "/users") and the variable undefined, the URL becomes the string undefined/users, a relative path that falls into the SPA fallback. Vite and Next.js replace public variables (VITE_*, NEXT_PUBLIC_*) at build time. Setting the variable on the server after the build doesn't change the JavaScript that was already generated. The details are in build-time vs runtime variables.

How do you diagnose it?#

In the Network tab. Open DevTools (F12), go to Network, filter by Fetch/XHR and click the failing request. Check the full URL (is it the API host?), the status, the Content-Type in the response headers and the Response tab. If you see your own app's HTML, it's cause 1; if you see the login screen, cause 3.

With curl. -i prints the status, the headers and the body, outside the browser:

bash
curl -i https://example.com/api/users
text
HTTP/2 200
content-type: text/html; charset=utf-8

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

Status 200 with text/html on an API route is the SPA fallback. Without -L, curl doesn't follow redirects, so a 302 with location: /login shows up directly. To test an authenticated route, add -H "Authorization: Bearer $TOKEN".

In code. Log res.status, res.url and the Content-Type before parsing. That is what the helper in the next section does.

How do you fix it on the client?#

Don't call res.json() blindly. MDN defines res.ok as true only for statuses 200 to 299, and Content-Type tells you whether the body is JSON. This helper checks both and turns the generic error into a message that says what arrived:

js
// api.js
export async function getJSON(url, options = {}) {
  const res = await fetch(url, {
    ...options,
    headers: { Accept: "application/json", ...options.headers },
  });

  if (res.status === 204) return null; // no body, nothing to parse

  const type = res.headers.get("content-type") ?? "";
  if (!/[/+]json\b/i.test(type)) {
    const snippet = (await res.text()).slice(0, 80);
    throw new Error(
      `Expected JSON from ${res.url}, got ${res.status} (${type || "no Content-Type"}): ${snippet}`,
    );
  }

  const data = await res.json();
  if (!res.ok) {
    throw new Error(`HTTP ${res.status} at ${res.url}: ${JSON.stringify(data)}`);
  }
  return data;
}

Instead of Unexpected token '<', the error now reads Expected JSON from https://example.com/api/userz, got 200 (text/html; charset=utf-8): <!DOCTYPE html>..., and the diagnosis is done. JSON error responses are still parsed, so the API's message isn't lost.

Also validate the base URL before using it, so a broken build fails with a clear sentence:

js
// config.js
export const API_URL = import.meta.env.VITE_API_URL;

if (!API_URL) {
  throw new Error("VITE_API_URL was not set at build time");
}

How do you fix it on the server?#

The API should always answer JSON, errors included, and the SPA fallback should never reach its routes. In Express 5, order solves it:

js
// server.js ("type": "module" in package.json)
import express from "express";
import path from "node:path";
import { fileURLToPath } from "node:url";

const dist = path.join(path.dirname(fileURLToPath(import.meta.url)), "dist");
const app = express();

// 1. API routes
app.get("/api/users", (req, res) => {
  res.json([{ id: 1, name: "Ana" }]);
});

// 2. Any other /api path gets a JSON 404, never index.html
app.use("/api", (req, res) => {
  res.status(404).json({ error: "not_found", path: req.originalUrl });
});

// 3. API errors in JSON too
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "internal_error" });
});

// 4. Only then: frontend files and the SPA fallback
app.use(express.static(dist));
app.get("/{*splat}", (req, res) => {
  res.sendFile(path.join(dist, "index.html"));
});

app.listen(process.env.PORT || 3000);

For expired sessions, same logic: on /api routes, answer a JSON 401 instead of redirecting to the login page, and let the frontend decide where to send the user.

In development with Vite, point the proxy at the backend with the same prefix your code uses:

js
// vite.config.js
import { defineConfig } from "vite";

export default defineConfig({
  server: {
    proxy: {
      "/api": "http://localhost:3000",
    },
  },
});

In production, pick one of two paths: one server delivers both the frontend and the API, as in the Express example, or the frontend calls the API's full URL, and the API then has to allow the frontend's domain through CORS.

How do you keep it from coming back?#

  • Use a single prefix for the API (/api) and make sure the SPA fallback never catches it.
  • Have the API answer JSON on 401, 404 and 500, with Content-Type: application/json.
  • Route every call through one helper that checks status and Content-Type.
  • Validate build variables when the app starts.
  • After each deploy, run curl -i against the API's main route.
  • When the HTML is a 500 error page, the real cause is in the server logs: how to read your app logs shows the way.

How to do this on Square Cloud#

On Square Cloud, an API is a web application: it has to listen on 0.0.0.0 on the port in the PORT variable and gets a *.squareweb.app subdomain with HTTPS. A curl -i against that subdomain tells you right away whether a route answers JSON or HTML.

If your frontend is a static site with vite.html, keep in mind that the runtime answers every path that isn't a file with that file, and that a static site doesn't run your code on the server. A fetch("/api/users") on the frontend's domain gets vite.html; without it, it gets 404.html, which is HTML too. The API has to be a separate web application, called by its full URL with CORS allowed, or the frontend can be served by the same Node.js server as the API, as in the example above.

There is no build step on the platform. If you build the frontend in your CI, set VITE_API_URL there; if the build runs in the start command (START) of a Node.js application, the application's environment variables are already set at that point, and Vite has to be in dependencies, because the install runs with NODE_ENV=production and leaves devDependencies out. Real-time logs show the error behind a 500, and 4xx/5xx error monitoring, included on every plan, shows when responses start failing. See the API hosting page.

API hosting

APIs in always-on containers, with no cold starts

API hosting

FAQs

What does Unexpected token '<' in JSON mean?

The text your code tried to parse starts with <, so it is HTML. It is almost always an error page, a login page or a SPA's index.html instead of the API response.

Why does it work locally but break in production?

In development, a proxy such as Vite's forwards /api to the backend. In production that proxy doesn't exist, so the same relative URL hits the server that serves the frontend and gets HTML. Use the API's full URL or have one server deliver both.

What is 'Unexpected end of JSON input'?

It is the same problem with an empty response: there is no body to parse, as in a 204 No Content or an error with no body. Check the status before calling res.json().

What does 'The string did not match the expected pattern' mean in Safari?

It is the generic message Safari shows when res.json() can't parse the body. The cause is the same as Unexpected token '<': the response wasn't JSON, and it is almost always an HTML page.

How do I see what the API actually returned?

Open the DevTools Network tab, click the request and look at the status, the Content-Type and the Response tab. In a terminal, curl -i prints the status, the headers and the body.

Next articleREST vs GraphQL: which to use for your APIREST exposes one URL per resource and uses HTTP caching; GraphQL has one endpoint where the client picks the fields. Compare caching, errors, N+1 and use cases.