An Astro integration to generate a Service Worker. Powered by Workbox.
MIT License
A minimal wrapper around Workbox to quickly add a service worker to your Astro static site. Get precached pages and offline support out of the box.
Add this package to your project:
npm install astrojs-service-worker
or yarn add astrojs-service-worker
Add astrojs-service-worker
to your astro.config.mjs integrations:
import { defineConfig } from "astro/config";
+ import serviceWorker from "astrojs-service-worker";
export default defineConfig({
+ integrations: [serviceWorker()],
});
That's it! A service worker that precaches all of your build's static assets will be generated. Page navigations will be served from the service worker's cache instead of making network calls, speeding up your page views and enabling offline viewing 🙌.
Note that when running astro dev
a no-op service worker is generated. Service workers interfere with hot module reloading (because they intercept the request for the updated asset), so this no-op service worker clears any existing workers for the page so hot module reloading works as expected.
astro build && astro preview
.Application
tab and then clicking the Service Workers
tab.Autoregister the service worker.
If false
, then the application must initialize the service worker by invoking register
. Set this to false
if you'd like to take control over when you service worker is initialized. You'll then need to add something like the following to your application:
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js");
}
Defaults to true
. Recommended: true
.
Defaults to GenerateSW
which will generate a service worker.
Note: injectManifest
is not supported at this time. If you would like it to be supported, please open an issue
Example:
import { defineConfig } from "astro/config";
import serviceWorker from "astrojs-service-worker";
export default defineConfig({
integrations: [
serviceWorker({
+ workbox: { inlineWorkboxRuntime: true }
})
],
});
You must serve your application over HTTPS in production environments. Service Workers must be served from the site's origin over HTTPS.
Some browsers special case localhost
, so this may not be necessary during local development. HTTPS is not handled by this library. You can use a reverse proxy like Nginx or Caddy if you want to setup HTTPS for local development.
The service worker origin constraint means that service workers can not control pages on a different subdomain. Eg mysite.com
can not be controlled by a service worker if that was served from a subdomain such as mycdn.mysite.com
. To learn more about how service workers work in general, read MDN's documentation.
My blog, tatethurston.com. You can use this site to get a sense of the capabilities enabled by this package. If you have any questions, feel free to open an issue.
PR's and issues welcomed! For more guidance check out CONTRIBUTING.md
See the project's MIT License.