Cloning Requests and Responses
You'll learn how to duplicate Request and Response objects so you can read their bodies multiple times.
The Problem: Bodies Are Single-Use
When you read a Request or Response body (with .json(), .text(), etc.), you consume it. The body stream can only be read once. If you try to read it again, you'll get an error: "body stream already read".
This becomes a problem when you need to:
- Log a request body before sending it
- Cache a response while also returning it
- Inspect response data in middleware, then pass it along
The Solution: .clone()
Both Request and Response objects have a .clone() method that creates an independent duplicate. The clone shares the same headers and configuration, but has a fresh body stream you can read separately.
Think of it like photocopying a document: the original and copy are identical at the moment of duplication, but you can highlight or mark up each one independently.
const response = await fetch('https://api.example.com/data');
// Clone before reading
const clone = response.clone();
// Read the original
const data = await response.json();
// Still can read the clone
const text = await clone.text();
Common Use Case: Caching
async function fetchWithCache(url) {
const response = await fetch(url);
// Clone before reading so we can cache and return
const cloneForCache = response.clone();
cache.put(url, cloneForCache);
return response.json(); // Original still readable
}
Important: Clone Before Reading
You must call .clone() before consuming either body. Once a stream is read, it's locked and cannot be cloned.
Key Takeaway: Use .clone() on Request or Response objects whenever you need to read the same body multiple times—clone first, then consume each copy independently.