Workbox - SPA - fallback to /index.html
Asked Answered
E

2

8

I'm using workbox with webpack to generate a service worker.

With the following code in webpack.config.js:

new WorkboxPlugin.InjectManifest({
  swSrc: "./src/sw.js"
}),

a service worker is generated nicely.

In ./src/sw.js, I have:

workbox.precaching.precacheAndRoute(self.__precacheManifest || []);

And all of my assets are precached nicely.

However, I have a single page application and I noticed that when refreshing the page while offline from a non-homepage route, the service worker doesn't respond. For example, when refreshing /page1 while offline doesn't work, but refreshing / does work.

How can I configure workbox to use a runtime strategy that uses /index.html as a fallback for HTML requests?

Note

Doing something like this:

new WorkboxPlugin.InjectManifest({
  swSrc: "./src/sw.js",
  navigationFallback: "/index.html"
})

does not work since navigationFallback is not a valid option in it's above usage.

{ message: '"navigationFallback" is not a supported parameter.'
Equilibrate answered 26/5, 2018 at 2:57 Comment(1)
register a route in the version of SW that u inject the manifest into. the regex can match the html's u wish to cover and the target can be 'index.html' . review docs for WB.registerRoute()Ambitendency
V
6

For workbox v4 or below, use workbox.routing.registerNavigationRoute (see another answer).

The recipe is changed in v5:

import {precacheAndRoute, createHandlerBoundToURL} from 'workbox-precaching'
import {NavigationRoute, registerRoute} from 'workbox-routing'


precacheAndRoute(self.__WB_MANIFEST)
registerRoute(new NavigationRoute(createHandlerBoundToURL('/index.html')))

Note: self.__WB_MANIFEST (renamed from self.__precacheManifest) is provided by WorkboxPlugin.InjectManifest.

Vashti answered 31/3, 2021 at 5:18 Comment(0)
E
14

Luckily, workbox has made this an easy solve.

If your site is a single page app, you can use a NavigationRoute to return a specific response for all navigation requests.

workbox.routing.registerNavigationRoute('/single-page-app.html');

In my case:

workbox.routing.registerNavigationRoute('/index.html');

Source: https://developers.google.com/web/tools/workbox/modules/workbox-routing#how_to_register_a_navigation_route

Equilibrate answered 26/5, 2018 at 12:1 Comment(0)
V
6

For workbox v4 or below, use workbox.routing.registerNavigationRoute (see another answer).

The recipe is changed in v5:

import {precacheAndRoute, createHandlerBoundToURL} from 'workbox-precaching'
import {NavigationRoute, registerRoute} from 'workbox-routing'


precacheAndRoute(self.__WB_MANIFEST)
registerRoute(new NavigationRoute(createHandlerBoundToURL('/index.html')))

Note: self.__WB_MANIFEST (renamed from self.__precacheManifest) is provided by WorkboxPlugin.InjectManifest.

Vashti answered 31/3, 2021 at 5:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.