If you want to learn everything you need to know about service workers, head over to serviceworkerbook.com and order my book, “Let’s Take This Offline”! Be sure to use custom-response for 10% off!

Note: this blog post assumes a working knowledge of service workers. If you need a refresher, I recommend looking here.

There might be times you want to send back a custom response from your service worker, rather than going out over the network. For example, you might not have a certain asset cached, while a user’s internet connection is simultaneously down. In this case, you can’t go over the network to fetch the asset, so you might want to send a custom response back to the client.

Let’s take a look at how we might implement a custom response.

This project demonstrates how you would return a custom response from a service worker. The basic idea is to make a fetch request to an API (in this case FayePI, which you should definitely check out). The service worker, however, sits between the client making requests and the API receiving them.

In this case, the service worker intercepts the fetch request and sends back a custom response – rather than going across the network.

Let’s look at the service worker to see how that works.

A service worker’s fetch event listener usually looks like this:

self.onfetch = function(event) {
        .then(function(cachedFiles) {
            if(cachedFiles) {
                return cachedFiles;
            } else {
                // go get the files/assets over the network
                // probably something like this: `fetch(event.request)`

Let’s change up what’s happening in the else-block of this code to return a custom response.

/* ... */
else {
    if(!event.request.url.includes(location.origin)) {
        var init = { "status" : 200 , "statusText" : "I am a custom service worker response!" };
        return new Response(null, init);

You might be wondering why the if-check is included there. We only want this to affect out-going requests, rather than requests coming to the app, which are likely requests for html files, and other assets. This quick check makes sure that the requested URL doesn’t match the URL of the app, so all of the static pages will still load properly.

Within that if-check, we are newing up a Response object. Here we go ahead and set the status code to 200 since it “worked” (that is, it reached our service worker and our service worker returned our custom response). We’ll also go ahead and change the status text, so we know that the response is actually coming from the service worker.

And that’s about it! Now you know how to return a custom response from your service worker! Be sure to check back soon to learn about how to cache more than just static files!

Thanks so much for reading! If you liked this post, you should head on over to serviceworkerbook.com and buy my book! Be sure to use custom-response for 10% off!