files/en-us/web/api/cachestorage/match/index.md
{{APIRef("Service Workers API")}}{{SecureContext_Header}}{{AvailableInWorkers}}
The match() method of the {{domxref("CacheStorage")}} interface checks if a given {{domxref("Request")}} or URL string is a key for a stored {{domxref("Response")}}.
This method returns a {{jsxref("Promise")}} for a {{domxref("Response")}}, or a {{jsxref("Promise")}} which resolves to undefined if no match is found.
You can access CacheStorage through the {{domxref("Window.caches")}} property in windows or through the {{domxref("WorkerGlobalScope.caches")}} property in workers.
Cache objects are searched in creation order.
[!NOTE]
caches.match()is a convenience method. Equivalent functionality is to call {{domxref("cache.match()")}} on each cache (in the order returned by {{domxref("CacheStorage.keys()", "caches.keys()")}}) until a {{domxref("Response")}} is returned.
match(request)
match(request, options)
request
options {{optional_inline}}
match
operation. The available options are:
ignoreSearch
true, the ?value=bar part of
https://example.com/?value=bar would be ignored when performing a match.
It defaults to false.ignoreMethod
true, prevents matching operations from validating the
{{domxref("Request")}} http method (normally only GET
and HEAD are allowed.) It defaults to false.ignoreVary
true, tells the matching operation not to perform VARY
header matching. In other words, if the URL matches you will get a match
regardless of whether the {{domxref("Response")}} object has a VARY
header or not. It defaults to false.cacheName
A {{jsxref("Promise")}} that resolves to the matching {{domxref("Response")}}. If
no matching response to the specified request is found, the promise resolves
with undefined.
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:
CacheStorage.match(). If so, serve that.v1 cache using open(), put the default
network request in the cache using {{domxref("Cache.put","Cache.put()")}} and return a
clone of the default network request using return response.clone(). The
last is necessary because put() consumes the response body.self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
// caches.match() always resolves
// but in case of success response will have value
if (response !== undefined) {
return response;
}
return fetch(event.request)
.then((response) => {
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
let responseClone = response.clone();
caches
.open("v1")
.then((cache) => cache.put(event.request, responseClone));
return response;
})
.catch(() => caches.match("/gallery/myLittleVader.jpg"));
}),
);
});
{{Specifications}}
{{Compat}}