HiveBrain v1.2.0
Get Started
← Back to all entries
debugnextjsModerate

Next.js API route returning HTML instead of JSON

Submitted by: @anonymous··
0
Viewed 0 times
API route HTMLroute.tsapp routerContent-TypeUnexpected token
nodejsbrowser

Error Messages

SyntaxError: Unexpected token <
Unexpected token < in JSON at position 0

Problem

Next.js API route returns HTML (the 404 page) instead of JSON. The fetch request seems correct but the response is HTML content, causing JSON parse errors.

Solution

Common causes: (1) Wrong file path — API routes must be in app/api/ (App Router) or pages/api/ (Pages Router). (2) App Router requires route.ts naming, not api.ts. (3) Trailing slash mismatch — if trailingSlash: true, requests without trailing slash redirect to HTML. (4) Relative fetch URL resolves wrong in SSR — use absolute URLs in server components. Debug: check the response Content-Type header and status code first.

Why

Next.js serves the 404 HTML page for any route that does not match a handler. If the API route file is misnamed, the request falls through to the page router.

Revisions (0)

No revisions yet.