Offline Fallback Hugo PWA

Hi Everyone, I’ve been wanting to bring my HUGO site to the Google Play Store. For that I need to be able to provide an offline fallback page. I’ve spent the last week looking for solutions and I still can’t figure out why I can’t make it work.

  1. The offline page (/offline) has 0 dependency. It’s very plain HTML
<!DOCTYPE html>
<html>
 <head>
  <title>{{ .Title }}</title>
 </head>
 <body>
    <h1>{{ .Title }}</h1>
    {{ .Content }}
    <script>
      window.addEventListener('load', () => {
          if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register('sw.js');
      }
      });
</script>
 </body>
</html>

I have a service worker setup and seems to be caching the offline page when loading the homepage

const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
// Customize this with a different URL if needed.
const OFFLINE_URL = "offline";

self.addEventListener("install", (event) => {
  event.waitUntil(
    (async () => {
      const cache = await caches.open(CACHE_NAME);
      // Setting {cache: 'reload'} in the new request ensures that the
      // response isn't fulfilled from the HTTP cache; i.e., it will be
      // from the network.
      await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
    })()
  );
  // Force the waiting service worker to become the active service worker.
  self.skipWaiting();
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      // Enable navigation preload if it's supported.
      // See https://developers.google.com/web/updates/2017/02/navigation-preload
      if ("navigationPreload" in self.registration) {
        await self.registration.navigationPreload.enable();
      }
    })()
  );

  // Tell the active service worker to take control of the page immediately.
  self.clients.claim();
});

self.addEventListener("fetch", (event) => {
  // Only call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === "navigate") {
    event.respondWith(
      (async () => {
        try {
          // First, try to use the navigation preload response if it's
          // supported.
          const preloadResponse = await event.preloadResponse;
          if (preloadResponse) {
            return preloadResponse;
          }

          // Always try the network first.
          const networkResponse = await fetch(event.request);
          return networkResponse;
        } catch (error) {
          // catch is only triggered if an exception is thrown, which is
          // likely due to a network error.
          // If fetch() returns a valid HTTP response with a response code in
          // the 4xx or 5xx range, the catch() will NOT be called.
          console.log("Fetch failed; returning offline page instead.", error);

          const cache = await caches.open(CACHE_NAME);
          const cachedResponse = await cache.match(OFFLINE_URL);
          return cachedResponse;
        }
      })()
    );
  }
});

And it seems to work!

Is there something in the way Hugo deals with routing or fallback that may be interfering? If not, are there resources to set up fallback pages for Offline with HUGO?

Hi,
Have you got this solution live to have a look? could you provide a link?

Also, the service worker shall be loaded in the head (<head>) of the page not in the body as I am aware. In debug do you have anything under the Service Workers section?

This approach is quite nice.
I ignored offline cache in my approach, but would like to explore it and hopefully benefit from that as well.

Hi @idarek , I went for offline support because I want to publish to the Google Play Store and it’s a pre-requisite. After talking with a friend and debugging for like 30 minutes…we discovered that the only thing missing was the trailing slash! I believe Cloudflare pages has an automating 308 redirect for all URL that doesn’t finish with it.

After 20hrs of trial and error…all I had to do is this:

const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
const OFFLINE_URL = "offline/";

and it worked!

1 Like