files/en-us/web/api/cache/put/index.md
{{APIRef("Service Workers API")}}{{SecureContext_Header}}{{AvailableInWorkers}}
The put() method of the
{{domxref("Cache")}} interface allows key/value pairs to be added to the current
{{domxref("Cache")}} object.
Often, you will just want to {{domxref("Window/fetch", "fetch()")}} one or more requests, then add the result straight to your cache. In such cases you are better off using {{domxref("Cache.add","Cache.add()")}}/{{domxref("Cache.addAll","Cache.addAll()")}}, as they are shorthand functions for one or more of these operations.
fetch(url).then((response) => {
if (!response.ok) {
throw new TypeError("Bad response status");
}
return cache.put(url, response);
});
[!NOTE]
put()will overwrite any key/value pair previously stored in the cache that matches the request.
[!NOTE] {{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} do not cache responses with
Response.statusvalues that are not in the 200 range, whereasCache.putlets you store any request/response pair. As a result, {{domxref("Cache.add")}}/{{domxref("Cache.addAll")}} can't be used to store opaque responses, whereasCache.putcan.
put(request, response)
request
response
A {{jsxref("Promise")}} that resolves with undefined.
http or https.This example is from the MDN simple-service-worker example (see simple-service-worker running live). Here we wait for a {{domxref("FetchEvent")}} to fire. We construct a custom response like so:
v1 cache using open(), put the default
network request in the cache using Cache.put() and return a
clone of the default network request using return response.clone(). Clone
is needed because put() consumes the response body.let response;
const cachedResponse = caches
.match(event.request)
.then((r) => (r !== undefined ? r : fetch(event.request)))
.then((r) => {
response = r;
caches.open("v1").then((cache) => cache.put(event.request, response));
return response.clone();
})
.catch(() => caches.match("/gallery/myLittleVader.jpg"));
{{Specifications}}
{{Compat}}