Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: Service worker (custom Astro integration) #242

Open
wants to merge 7 commits into
base: main
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import sitemap from '@astrojs/sitemap';
import type { PluginOption } from 'vite';
import { isPreview } from './config/preview';
import pkg from './package.json';
import serviceWorker from './config/astro/service-worker-integration.ts';

const productionUrl = `https://${ pkg.name }.pages.dev`; // overwrite if you have a custom domain
const localhostPort = 4323; // 4323 is "head" in T9
Expand Down Expand Up @@ -50,7 +51,10 @@ export default defineConfig({
// @see https://docs.astro.build/en/guides/images/#configure-no-op-passthrough-service
service: passthroughImageService()
},
integrations: [sitemap()],
integrations: [
sitemap(),
serviceWorker()
],
output: isPreview ? 'server' : 'static',
server: { port: localhostPort },
site: siteUrl,
Expand Down
67 changes: 67 additions & 0 deletions config/astro/service-worker-integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { APIRoute, AstroIntegration } from 'astro';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import * as esbuild from 'esbuild';

const filenamePath = (filename: string) => fileURLToPath(new URL(join('../../', filename), import.meta.url));
const srcFilename = filenamePath('src/assets/service-worker.ts');
const outFilename = filenamePath('dist/service-worker.js');

export default function serviceWorkerIntegration(): AstroIntegration {
return {
name: 'service-worker',
hooks: {
'astro:config:setup': async ({
command,
injectRoute,
addWatchFile,
}) => {
const isDevelopment = command === 'dev';
if (isDevelopment) {
addWatchFile(srcFilename);
injectRoute({
pattern: '/service-worker.js',
entrypoint: import.meta.url,
});
}
},
'astro:build:done': async () => {
try {
await esbuild.build({
entryPoints: [srcFilename],
outfile: outFilename,
target: ['es2020'],
bundle: true,
minify: true,
allowOverwrite: true,
sourcemap: true,
});
} catch (e) {
console.error('Failed to build service worker');
console.error(e);
process.exit(1);
}
},
},
};
}

export const GET: APIRoute = async () => {
const output = await esbuild.build({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The esbuild.build config between dev and prod are (and should be) mostly the same (only minify and sourcemap are different). Should we move the shared config up to the root?

const buildConfig = {
    entryPoints: [srcFilename],
    outdir: outFilename,
    target: ['es2020'],
    bundle: true,
    write: false,
    allowOverwrite: true,
}

and use that in both places to keep everything in sync?, like:

const output = await esbuild.build({
   ...buildConfig,
   minify: false,
   sourcemaps: false,
});

entryPoints: [srcFilename],
outdir: outFilename,
target: ['es2020'],
bundle: true,
minify: false,
write: false,
allowOverwrite: true,
sourcemap: false,
});

return new Response(output.outputFiles[0].contents, {
status: 200,
headers: {
'Content-Type': 'application/javascript',
},
});
};
6 changes: 6 additions & 0 deletions docs/assets.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,9 @@ import Icon from '@components/Icon/';
}
</style>
```

## Service Worker

Head Start provides a fully customisable service worker in [`src/assets/service-worker.ts`](../src/assets/service-worker.ts) that's automatically bundle and served as `/service-worker.js` (in both development and production) and registered in each web page (using inline script in `src/layouts/PerfHead`). The service worker uses the low-level [Workbox modules](https://developer.chrome.com/docs/workbox/modules) for fine-grained control.

For more background see [decision log on service worker](./decision-log/2025-01-11-service-worker.md).
13 changes: 13 additions & 0 deletions docs/decision-log/2025-01-11-service-worker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Service Worker

**Implement Service Worker using our own Astro Integration with Workbox modules for maximum control.**

- Date: 2025-01-11
- Alternatives Considered: existing integrations [`astrojs-service-worker`](https://github.com/tatethurston/astrojs-service-worker) and [`zastro-service-worker`](https://github.com/zachhandley/astro-service-worker)
- Decision Made By: [Declan](https://github.com/decrek), [Jurgen](https://github.com/jurgenbelien), [Jasper](https://github.com/jbmoelker)

## Decision

Known existing Astro integrations for Service Workers are [`astrojs-service-worker`](https://github.com/tatethurston/astrojs-service-worker) and [`zastro-service-worker`](https://github.com/zachhandley/astro-service-worker). These integrations both use [`generateSW` from `workbox-build`](https://developer.chrome.com/docs/workbox/modules/workbox-build#generatesw), which only allows modifying the service worker through configuration.

To give developers using Head Start more control over their service worker we've decided add our own [Astro Integration](../../config/astro/service-worker-integration.ts) which uses an actual file as a source ([`assets/service-worker.ts`](../../src/assets/service-worker.ts)) which developers can customise. By using low-level [Workbox modules](https://developer.chrome.com/docs/workbox/modules) this control is extended further.
Loading