JavaScript Object Notation (JSON) is the universal data interchange format of modern web services. When receiving responses via the Fetch API, reading and parsing JSON safely requires understanding response body streams and error handling.
1. The response.json() Method
The HTTP response body returned by fetch() is a readable stream. To parse this stream into a native JavaScript object, invoke response.json():
A crucial architectural detail of the Fetch API is that the body stream can only be consumed once. Attempting to read it a second time throws a TypeError:
JavaScript
1const response =awaitfetch('/api/data');
2
3const json =await response.json();// Consumed the stream!
4// const text = await response.text(); // ERROR: TypeError: Failed to execute 'text' on 'Response': body stream already read!
The Solution: Cloning the Response
If you need to read the body multiple times (for example, for logging and parsing):
JavaScript
1const response =awaitfetch('/api/data');
2const clonedResponse = response.clone();// Clones the stream before reading
If a server crashes and returns an HTML error page (e.g., 502 Bad Gateway from Nginx) instead of JSON, response.json() will throw a SyntaxError: Unexpected token < in JSON.