Experiment: Creating REST API in browser with Google’s Workbox

Dmytro Sych
3 min readAug 4, 2018

--

This post is not meant to be highly educational in nature. In fact, I can hardly think of any applications it could have in real world. However, what this post in intended to do is bring in-depth understanding of Workbox and Service Workers through unconventional application of the technologies.

Theory

We all the conventional model of how web apps interact with back-end. There is some kind of API that exposes endpoints to which the app is able to make requests.

If we introduce Service Workers into the picture, the above would change into:

sw

In this case, all requests are being intercepted by SW which decides whether to let the request fall through to the network or generate response in-place e.g. deliver files from cache.

So what does Workbox has to do with anything? Good question, Workbox is a user friendly API built on top of Js implementation of SW. However, it does no stop there, in reality, Workbox can do:

  • Precaching
  • Routing
  • Defines multiple strategies of content delivery
  • Cache expiration
  • Sync of your local SW with the global instance

There is a LOT more stuff you can do with Workbox, check out this AWESOME project here.

Preparation

The module I will be using today is Routing. Usually, you would use Routing with one of the pre-defined Strategies. But where is fun in that? Thankfully, we can also define our own strategy by supplying method to registerRoute method.

I am using Parcel to bundle my app, since it is 0 config.

Let’s get down to it

Here is the code for our index.html and index.js pages. I will not go into details, since they have exhaustive comments. Just going give high level overview:

  • index.html defines to buttons that are wired to make fetch requests to /hello-world endpoint.
  • index.js registers SW and add listeners to buttons.

Meat and potatoes aka. SW code

You can read comments and I will focus on how Workbox operates here because nobody wants to read docs=)

Above we witness to calls of registerRoute method with 3 parameters:

  1. RegEx that will be used to match the incoming url’s pathname.
  2. Function to be executed should the route match. Function is supposed to return Response object or Promise that resolves to Response.
  3. Method of the request. Workbox gives you flexibility to decide different implementations for various methods.

Now every time I press either of buttons, HTTP request is initiated to hello-world endpoint. It is intercepted by SW:

That’s it, thanks for reading!🎉

You can find entire example here.

Found an error? Do let me know in comments!

Originally published at gist.github.com.

--

--