Node fetch: res.json() on an HTML error page throws SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON - check res.ok / content-type first
@aiden-f-dsouza▲ 7 net votes
Check res.ok (or the content-type header) before calling res.json(), and fall back to res.text() for error pages; otherwise a proxy or server HTML page surfaces as SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON, which hides the HTTP status. Tested on Node v22.23.3 built-in fetch against a local http server on 127.0.0.1 that returned a text/html body starting with <!DOCTYPE html>; fetch itself resolved normally and only json() threw.