Skip to content
Raisalon

Software Engineering

Fix “Unexpected token <” when fetch expects JSON

Trace a fetch JSON parse error to an HTML response. Use status, redirect history and content type to distinguish a login page, a missing route and a fallback.

Author
3 min read

An “Unexpected token <” error from response.json() usually means your application tried to parse HTML as JSON (JavaScript Object Notation). The unexpected character is often the opening angle bracket of <!doctype html>. Find out which page the server actually sent before changing your JSON parser.

Read the failed response in the Network panel

Open the browser’s Network panel, preserve the log, and reproduce the failure. Select the request initiated by your code. Inspect its request URL, final URL, status, response Content-Type and the first line in the Response tab. These fields let you distinguish three common failures that otherwise produce nearly identical console output.

What the browser received Likely explanation What to check next
404 and an HTML error page The request missed the endpoint Verify the path, deployment base path and HTTP method.
200 and a sign-in page after a redirect The session expired or authentication interrupted the request Inspect the redirect chain and the endpoint’s unauthenticated response contract.
200 and the site’s home page at the original URL A navigation fallback handled the request Check rewrite ordering and whether the API route exists in this deployment.

A 200 status only tells you the request reached a successful HTTP response. A sign-in form and an application shell can both be valid 200 responses. Likewise, fetch normally resolves its promise when a server returns a 404 or 500. You have to inspect response.ok to decide whether that status is acceptable. MDN guide to using Fetch

Make the mismatch reproducible

Run this in a modern browser console. It constructs the same kind of response a navigation fallback could return. There is no network dependency. The catch block prints the runtime’s own syntax-error message, whose wording varies between JavaScript engines.

const wrongPage = new Response('<!doctype html><title>Home</title>', {
  status: 200,
  headers: { 'Content-Type': 'text/html; charset=utf-8' },
});

try {
  await wrongPage.json();
} catch (error) {
  console.log(error.name, error.message);
}

Calling json() consumes the body. If you then call text() on the same response while debugging, the second read fails because the stream has already been read. Inspect the response in the Network panel, or clone it before the first read when you need two independent consumers in a small test. MDN Response.json reference

Give your JSON client a clear contract

The helper below expects a successful response with a JSON body. It accepts ordinary application/json and structured types such as application/problem+json. It strips media-type parameters before checking. The status and media type in its error messages are enough to start diagnosis without dumping an entire HTML document into logs.

async function fetchJson(url) {
  const response = await fetch(url, {
    headers: { Accept: 'application/json' },
  });
  const type = (response.headers.get('content-type') || '')
    .split(';')[0].trim().toLowerCase();

  if (!response.ok) throw new Error('HTTP ' + response.status);
  if (response.status === 204 || response.status === 205) {
    throw new Error('Expected JSON but received an empty response');
  }
  if (type !== 'application/json' && !type.endsWith('+json')) {
    throw new Error('Expected JSON, received ' + (type || 'no content type'));
  }
  return response.json();
}

The Accept header tells the server what the client wants. It cannot turn an HTML fallback into a JSON endpoint. A response can also declare JSON while containing invalid syntax. If the media type looks correct and parsing still fails, inspect the raw text for a truncated object, a trailing comma or an HTML error emitted after headers were set. Use a sanitized example if you paste a payload into a JSON formatter.

Fix the layer that supplied the page

For a missing route, request the same URL directly on the deployed site and confirm the API exists there. A development proxy can make a relative URL work locally while the static host has no matching backend. For a fallback, ensure the host sends API paths to their intended handler before applying its general navigation rewrite.

For an expired session, agree on the intended API behavior with the backend. A browser navigating to a document can use a sign-in redirect. A data client usually needs a recognizable unauthenticated status so it can decide when to send the user to sign-in. For an endpoint deliberately returning 204 on success, use a separate no-content code path in the caller.

Resolve a relative URL from the failing page

A relative path that works on a homepage can change meaning on a nested route. Consider an article served from https://example.org/blog/debugging/. From that location, fetch('api/posts') requests /blog/debugging/api/posts. If the host sends its ordinary article shell for unknown paths, the console reports a JSON syntax error even though the bug is the request address.

const article = 'https://example.org/blog/debugging/';
console.log(new URL('api/posts', article).pathname);
// /blog/debugging/api/posts
console.log(new URL('/api/posts', article).pathname);
// /api/posts

Use the second form when the service really lives at the origin root. If the app is deployed under a prefix such as /docs/ and its endpoint lives there too, construct the URL from that configured base. Test one nested route in the deployed layout. A successful request from the homepage proves only that the URL resolved correctly from that document.

Next steps

Add a client test for a 200 HTML response alongside the ordinary successful JSON case. Also cover your endpoint’s expected empty or unauthorized response. That turns a confusing parser exception into a specific failure at the boundary where your application received the wrong representation.

Share

Written by