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
- To fix this, you need to manipulate the PWA config in
vite.config.tsand the customservice-workerfile. After setting up the basic PWA, I added the following to yourvite.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}'
],
}
})
],
});
- Notice the
prerendered/**/*.{html,json}in theglobPatternsarray, this tellsvite-plugin-pwato cache the prerendered data (typically in the form of__data.jsonfiles) so that the app can work offline. This should have been enough, but for some reason you need this weird hack in yourservice-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)
Happy new year 🎉
You’re using auto update, the code should be:
@userquin Okay, I finally fixed it. All we just needed to do was:
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.svelteor 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: trueto kit pwa options: you can also removeinjectManifestoptions, looks like your options are the default onesI will do that once I get back, out rn
And working offline:
ok, the fix will work for
__data.jsonfiles, kit is generating them since we’ve the entries in the sw precache manifest.I’m going to update the
buildGlobPatternsfunction to includejsonandjsfiles and removing also'prerendered/dependencies/'prefix in the manifest transform: