cloudflare-docs
cloudflare-docs copied to clipboard
[Workers] Cache API: Clarify that the response needs to be cloned to prevent "Body has already been used" when returning from Worker
Which Cloudflare product does this pertain to?
Workers
Existing documentation URL(s)
- https://developers.cloudflare.com/workers/runtime-apis/cache/#put
- https://canary.discord.com/channels/595317990191398933/779390076219686943/1072677873908990023 (cloudflare dev discord)
Section that requires update
Cache#Put Method
What needs to change?
Using the following example:
const httpResponse = new Response(JSON.stringify({url: "foo.bar"}), {
headers: {
'Content-Type': 'application/json'
}
});
await cache.put(request, httpResponse);
return httpResponse;
Causes the error Uncaught (in response) TypeError: Body has already been used. It can only be used once. Use tee() first if you need to read it twice..
I had to search the Discord to find a solution for that.
How should it change?
Provide an more extensive example where this is shown, or put a mention into the docs, that a response object that is being put into the cache and then returned to the user needs to be cloned (i.e.: await cache.put(request, httpResponse.clone());), since otherwise the mentioned issue arises when trying to return the response object to the requesting client afterwards.
Imo this is an easy to miss gotcha in a common usecase.
Additional information
No response