Open meticoeus opened 1 year ago
For anyone looking for a temporary if very hacky workaround, I've added a fetch event handler in my service worker to work around this:
// service-worker.ts
// add this before workbox registerRoute(...)
self.addEventListener('fetch', (event: FetchEvent) => {
const url = new URL(event.request.url)
if (url.pathname.includes('/_app/') && !url.pathname.startsWith('/_app/')) {
url.pathname = replaceBeforeSubstring(url.pathname, '/_app/')
return event.respondWith(caches.match(url))
}
})
I am struggling with this exact same issue using generateSW
. I tried adding the above snippet (thanks @meticoeus) to the generated service worker, but didn't seem to fix it for me unfortunately. Maybe it's necessary to switch to injectManifest
?
I'm prerendering and precaching the root page and setting navigateFallback
to '/'
as listed in the precache manifest. Still, any redirects, manual page refreshes or errors thrown in page load functions leads to the service worker looking for ./_app/...
in the current route instead of the root. For me this happens not only with dynamic routes, but ALL non-prerendered routes that are not at the root.
I tried to add dynamic routes to navigateFallbackDenylist
, which at least leads to page refreshes and SvelteKit error pages working like normal when online, but still does not work offline (and leads to a server request that shouldn't be necessary, as all it does is return an HTML shell with the corrected path to _app
).
Did anyone find a stable solution to this? Or is the better bet to just prerender and handle everything dynamic in regular Svelte components?
Found the answer! The issue seems entirely related to the SvelteKit build process and not the service worker / PWA plugin.
Setting this
const config = {
kit: {
...
paths: {
relative: false,
},
...
},
}
in svelte.config.js
has completely resolved it for me and now the service worker behavior matches the regular SvelteKit behavior.
The generated asset links on dynamic pages are relative to the current directory instead of the root, resulting in prefixing the current URL to the asset requests which do not exist.
Navigating to pages with the client side router works correctly. The only problem is when you open the page to a page that isn't prerendered or refresh the page on a page that isn't prerendered that you encounter the problem.
I've tested the normal example produced with
npm create svelte@latest my-app
and it correctly generates relative links to the assets.Issue reproduction: https://github.com/meticoeus/sveltekit. See the modified example
I've made minimum modifications to the example to switch to the new auto adapter and add a dynamic route page that imports a component to show the problem.
Example generated html for route
/about/[id]
in.svelte-kit/output/
: