sveltekit: Precaching bug with `adapter-static` and `load()` functions

The main problem

There’s a specific bug when using load() functions along with prerendering and the static-adapter that I spent hours trying to fix, it occurs primarily due to @vite-pwa/sveltekit not being able to figure out how to cache the returned data from the load(), typically stored in:

.svelte-kit/output/prerendered/dependencies/{page-route}/__data.json

This causes the app to break when offline and navigating to a page that depends on that data.

The hacky fix

  1. To fix this, you need to manipulate the PWA config in vite.config.ts and the custom service-worker file. After setting up the basic PWA, I added the following to your vite.config.ts:
export default defineConfig({
  plugins: [
    sveltekit(),
    SvelteKitPWA({
      /* other config */
      injectManifest: {
        globPatterns: [
          'client/**/*.{js,css,ico,png,svg,webp,webmanifest,ttf,woff,woff2}',
          'prerendered/**/*.{html,json}'
        ],
      }
    })
  ],
});
  1. Notice the prerendered/**/*.{html,json} in the globPatterns array, this tells vite-plugin-pwa to cache the prerendered data (typically in the form of __data.json files) so that the app can work offline. This should have been enough, but for some reason you need this weird hack in your service-worker.ts:
/// <reference lib="WebWorker" />
/// <reference types="@sveltejs/kit" />

import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
declare let self: ServiceWorkerGlobalScope;

const manifest = self.__WB_MANIFEST;

manifest.forEach((entry) => {
	if (typeof entry === 'object' && entry.url.endsWith('__data.json')) {
		entry.url = entry.url.replace(/^prerendered\/dependencies\//, '');
	}
});

cleanupOutdatedCaches();
precacheAndRoute(manifest, { ignoreURLParametersMatching: [/.*/] });

self.addEventListener('message', (event) => {
	if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
});

registerRoute(/.*/, new StaleWhileRevalidate());

This hack is necessary because the __data.json files are stored in the prerendered/dependencies/ folder, and the service worker’s default behaviour incorrectly configures their URLs. This hack manually alters the URLs so that the service worker can cache them correctly.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 54 (28 by maintainers)

Most upvoted comments

Happy new year 🎉

You’re using auto update, the code should be:


self.skipWaiting()
self.addEventListener('activate', (event) => {
	event.waitUntil(self.clients.claim());
	console.log('Service worker activated');
});

/* THIS IS USED FOR PROMPT FOR UPDATE: CLIENTS WILL NOT EMIT THIS EVENT
self.addEventListener('message', (event) => {
	if (event.data && event.data.type === 'SKIP_WAITING') self.skipWaiting();
});
*/

@userquin Okay, I finally fixed it. All we just needed to do was:

self.addEventListener('activate', (event) => {
	event.waitUntil(self.clients.claim());
	console.log('Service worker activated');
});

The service worker wasn’t taking control on the initial page load, and therefore unable to serve cache resulting in errors as the requests were not being passed to it anyways.

There was no need to modify the registration logic in the root +layout.svelte or even include the version file in the kit config. Updated the repro to reflect all this with default config and still working.

Hey, it works!

I forgot to use registerRoute() on the paths so the sw wasn’t participating in the fetch at all. My bad.

Once I added that, with v0.6.7, it works properly. Thank you very much!

Ohk, need to head out for a bit, will get back in an hour or two and add the icons

Try adding includeVersionFile: true to kit pwa options: you can also remove injectManifest options, looks like your options are the default ones

I’m going to release a patch version, in the meantime you can check it in your local with this dependency: https://pkg.pr.new/@vite-pwa/sveltekit@a7c0605 (I guess once PR merged the pkg.pr.new is removed)

I will do that once I get back, out rn

And working offline:

image

ok, the fix will work for __data.json files, kit is generating them since we’ve the entries in the sw precache manifest.

I’m going to update the buildGlobPatterns function to include json and js files and removing also 'prerendered/dependencies/' prefix in the manifest transform:

function buildGlobPatterns(globPatterns?: string[]) {
  if (globPatterns) {
    if (!globPatterns.some(g => g.startsWith('prerendered/')))
      globPatterns.push('prerendered/**/*.{html,json,js}')

    if (!globPatterns.some(g => g.startsWith('client/')))
      globPatterns.push('client/**/*.{js,css,ico,png,svg,webp,webmanifest}')

    if (!globPatterns.some(g => g.includes('webmanifest')))
      globPatterns.push('client/*.webmanifest')

    return globPatterns
  }

  return ['client/**/*.{js,css,ico,png,svg,webp,webmanifest}', 'prerendered/**/*.{html,json,js}']
}