MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

FetchEvent.respondWith()

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

The respondWith() method of FetchEvent prevents the browser's default fetch handling, and allows you to provide (a promise for) a Response yourself.

In most cases you can provide any response that the receiver understands (as in, if an <img> initiates the request, the response body needs to be image data), however for security reasons, there are a few global rules:

Syntax

fetchEvent.respondWith(
  // Promise that resolves to a Response.
​)

Returns

Void.

Parameters

A Promise for a Response.

Examples

This fetch event tries to return a response from the cache API, falling back to the network otherwise.

addEventListener('fetch', event => {
  // Prevent the default, and handle the request ourselves.
  event.respondWith(async function() {
    // Try to get the response from a cache.
    const cachedResponse = await caches.match(event.request);
    // Return it if we found one.
    if (cachedResponse) return cachedResponse;
    // If we didn't find a match in the cache, use the network.
    return fetch(event.request);
  }());
});

Specifications

Specification Status Comment
Service Workers
The definition of 'respondWith()' in that specification.
Editor's Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 40.0 44.0 (44.0)[1] No support 24 No support
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support ? 44.0 (44.0) (Yes) No support ? No support 44.0

[1] Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR.)

See also

Document Tags and Contributors

 Last updated by: jaffathecake,