Course contentsShow
← Web Development
Lesson 858 of 2,98215. Browser NetworkingFree lesson

Response Cloning

Understanding why and how to use response.clone() when consuming response bodies multiple times.

Response Cloning

You'll learn why you can't read a response body twice and how response.clone() solves that problem.

The One-Time-Use Problem

When you call a response body method like response.json() or response.text(), the response body is consumed. Think of it like drinking from a juice box—once you've sucked it dry, there's nothing left. The stream has been read, and you can't read it again.

This becomes a problem when you need to use the response multiple times. For example, maybe you want to cache a response and return the data to your app. Or log the raw text while also parsing JSON.

What response.clone() Does

The clone() method creates an identical copy of the response object before it's been consumed. Now you have two separate juice boxes—you can drink from one while saving the other.

fetch('/api/user')
  .then(response => {
    const clonedResponse = response.clone();
    
    // Use the clone for caching
    caches.open('api-cache').then(cache => {
      cache.put('/api/user', clonedResponse);
    });
    
    // Use the original for parsing
    return response.json();
  })
  .then(data => console.log(data));

When to Clone

Clone before consuming either copy. Once you call .json() or .text() on a response, it's too late—the body is gone. Always clone first if you know you'll need the response more than once.

Key Takeaway: Response bodies can only be read once; use response.clone() before consuming to create an independent copy you can read separately.