workbox-routing. Router
The Router takes one or more Routes and allows you to apply that routing logic to determine the appropriate way of handling requests inside of a service worker.
It also allows you to define a "default" handler that applies to any requests that don't explicitly match a Route
, and a "catch" handler that responds to any requests that throw an exception while being routed.
You can use the handleRequest()
method to pass a FetchEvent
through the router and ultimately get a "routed response" back. If you'd like this to be handled automatically for you, calling
addFetchListener()
will cause the Router
to respond to fetch
events.
If a request matches multiple routes, precedence will be given to the last-registered route.
Constructor
Router
new Router()
Constructs a new Router
instance, without any registered routes.
Example
// The following example sets up two routes, one to match requests with
// "assets" in their URL, and the other for requests with "images", along
// different runtime caching handlers for each.
// Both the routes are registered with the router, and any requests that
// don't match either route will be handled using the default NetworkFirst
// strategy.
// "If a request matches both routes, the last route will be used to handle
// the request, in this case, the "images" handler would take precedence.
const assetRoute = new RegExpRoute({
regExp: /assets/,
handler: new workbox.runtimeCaching.StaleWhileRevalidate(),
});
const imageRoute = new RegExpRoute({
regExp: /images/,
handler: new workbox.runtimeCaching.CacheFirst(),
});
const router = new workbox.routing.Router();
router.addFetchListener();
router.registerRoutes({routes: [assetRoute, imageRoute]});
router.setDefaultHandler({
handler: new workbox.runtimeCaching.NetworkFirst(),
});
Methods
addFetchListener
addFetchListener() returns boolean
This will register a fetch
event listener on your behalf which will check the incoming request to see if there's a matching route, and only respond if there is a match.
- Returns
-
boolean
Returnstrue
if this is the first time the method is called and the listener was registered. Returnsfalse
if called again, as the listener will only be registered once.
Example
const imageRoute = new RegExpRoute({
regExp: /images/,
handler: new CacheFirst(),
});
const router = new Router();
router.registerRoute({route: imageRoute});
router.addFetchListener();
handleRequest
handleRequest(input) returns (Promise containing Response or undefined)
This can be used to apply the routing rules to generate a response for a given request inside your own fetch
event handler.
Parameter |
|||||
---|---|---|---|---|---|
input |
Object Values in
|
- Returns
-
(Promise containing Response or undefined)
Returns a promise for a response, taking the registered routes into account. If there was no matching route and there's nodefaultHandler
, then returns undefined.
Example
const imageRoute = new RegExpRoute({
regExp: /images/,
handler: new CacheFirst(),
});
const router = new Router();
router.registerRoute({route: imageRoute});
self.addEventListener('fetch', (event) => {
event.waitUntil((async () => {
let response = await router.handleRequest({event});
// Do something with response, and then eventually respond with it.
event.respondWith(response);
})());
});
registerRoute
registerRoute(input)
Registers a single route with the router.
Parameter |
|||||
---|---|---|---|---|---|
input |
Object Values in
|
Example
router.registerRoute({
route: new Route({ ... })
});
registerRoutes
registerRoutes(input)
Registers an array of routes with the router.
Parameter |
|||||
---|---|---|---|---|---|
input |
Object Values in
|
Example
router.registerRoutes({
routes: [
new RegExpRoute({ ... }),
new ExpressRoute({ ... }),
new Route({ ... }),
]
});
setCatchHandler
setCatchHandler(input)
If a Route throws an error while handling a request, this handler
will be called and given a chance to provide a response.
Parameter |
|||||
---|---|---|---|---|---|
input |
Object Values in
|
Example
router.setCatchHandler(({event}) => {
if (event.request.mode === 'navigate') {
return caches.match('/error-page.html');
}
return Response.error();
});
setDefaultHandler
setDefaultHandler(input)
An optional handler
that's called by default when no routes explicitly match the incoming request.
If the default is not provided, unmatched requests will go against the network as if there were no service worker present.
Parameter |
|||||
---|---|---|---|---|---|
input |
Object Values in
|
Example
router.setDefaultHandler({
handler: new workbox.runtimeCaching.NetworkFirst()
});
unregisterRoute
unregisterRoute(input)
Unregisters a single route with the router.
Parameter |
|||||
---|---|---|---|---|---|
input |
Object Values in
|
Example
const route = new RegExpRoute({ ... });
router.registerRoute({route});
// Later, if you no longer want the route to be used:
router.unregisterRoute({route});
unregisterRoutes
unregisterRoutes(input)
Unregisters an array of routes with the router.
Parameter |
|||||
---|---|---|---|---|---|
input |
Object Values in
|
Example
const firstRoute = new RegExpRoute({ ... });
const secondRoute = new RegExpRoute({ ... });
router.registerRoutes({routes: [firstRoute, secondRoute]});
// Later, if you no longer want the routes to be used:
router.unregisterRoutes({routes: [firstRoute, secondRoute]});