4.2 Service Workers and Fetch API
# Fetch API And Service Workers
By far, the most important thing you will do with a service worker is to make it work as a proxy server. A proxy server is a server
that sits between your browser's webpage and the actual webserver that is sending the files. It has the ability to cache files for later use, manage when new versions of the file are needed, cache data in localStorage or an indexedDB, and basically provide an offline experience for the website.
The first step is to add an event listener for the fetch
event. This event is triggered EVERY time the browser sends a request for a file. Inside the event will be a Request object, which is the Request being sent from the browser. Now, our service worker gets to decide how to handle that request.
self.addEventListener('fetch', (ev) => {
//this function runs on every request from the browser.
console.log(ev.request);
//the event object contains a request property that is a Request Object.
});
2
3
4
5
MDN reference for Request Objects (opens new window)
MDN reference for Response Objects (opens new window)
The Request
object will contain a url
property with the full URL of the Request, a method
property that tells us if it was a GET
, POST
, PUT
, PATCH
, DELETE
, HEAD
, or OPTIONS
request, plus a mode
property that tells us if the request was cors
, no-cors
, same-origin
, or navigate
. The navigate
mode can be an important distinction. The user might be trying to leave the website or navigate to a different page within our site. The other modes have to do with downloading files that will be used within our page.
There is also a headers
property that contains important meta information about the request. These might be needed to make requests to the actual Server. The headers
can include things like the content-type
of the file being requested.
Once we have the request we have many options.
- Search the cache and return the file found there.
- Search the cache and if no matching file, do a fetch request for the file.
- Only forward the request on to the actual server and return a file from the server.
- Search the cache, return a file from there, and also forward the request to the server to get a new version of the requested file.
- Check if the user is online or offline and return different files based on the result.
To send anything back to the browser we would use the respondWith()
method that can be found on the fetch
event.
Here is a simple example showing a couple options.
Only the first
ev.respondWith()
call will actually run.
self.addEventListener('fetch', (ev) => {
//1. just forward the request to the actual server
ev.respondWith(ev.request);
//2. check the cache
// return the file from the cache if it exists
// if not, do a fetch, add to the cache and return to browser the fetched file
// remember to handle a failed fetch to the server
// pay attention to the nested `return` statements
ev.respondWith(
caches.match(ev.request).then((cacheResponse) => {
return (
cacheResponse ||
fetch(ev.request)
.then((fetchResponse) => {
//if the fetch fails...
if (!fetchResponse.ok) {
//return any failed fetch to the browser if you want
return fetchResponse;
//or throw an error and handle it in custom ways
throw new Error(fetchResponse.statusText);
}
//we have a file from the server
return caches.open('mycache').then((cache) => {
cache.put(ev.request, fetchResponse.clone());
//we have to make a copy of the response to put it in the cache
//then return the file to the browser
return fetchResponse;
});
})
.catch((err) => {
//had an error fetching the file
//what do you want to return to the browser request???
})
);
})
);
//end of ev.respondWith()
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Caches and Service Workers
We talked about the Cache API back in week 2. This first video is a review of that.
This second video is how to use the caches from inside a Service Worker to keep things in sync with the Service Worker Life Cycle.
# IndexedDB and Service Workers
We have already talked about IndexedDB, this video outlines how you can work with one from within a Service Worker.
# What to do this week
TODO
Things to do before next week
- Read and Watch all the course content for
4.1
,4.2
, and5.1
- Complete Hybrid 2