> ## Documentation Index
> Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Service Workers

> Progressive Web App (PWA) support with service workers.

Service workers enable offline support, push notifications, and Progressive Web App (PWA) functionality.

## Basic Service Worker

### Create Service Worker

```js theme={null}
// public/sw.js
self.addEventListener('install', (event) => {
  console.log('Service Worker installing')
})

self.addEventListener('activate', (event) => {
  console.log('Service Worker activating')
})

self.addEventListener('fetch', (event) => {
  // Handle fetch events
})
```

### Register in App

```js theme={null}
// src/main.ts
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js')
    .then(reg => console.log('SW registered', reg))
    .catch(err => console.log('SW registration failed', err))
}
```

### Configure Mizu

```go theme={null}
app.Use(frontend.WithOptions(frontend.Options{
    ServiceWorker: "sw.js",  // Sets proper scope headers
}))
```

## Caching Strategies

### Cache First

```js theme={null}
// sw.js
const CACHE_NAME = 'v1'

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  )
})
```

### Network First

```js theme={null}
self.addEventListener('fetch', (event) => {
  event.respondWith(
    fetch(event.request)
      .catch(() => caches.match(event.request))
  )
})
```

## Workbox

Use Workbox for production service workers:

```bash theme={null}
npm install workbox-cli -D
```

```js theme={null}
// workbox-config.js
module.exports = {
  globDirectory: 'dist/',
  globPatterns: ['**/*.{html,js,css,png,jpg,svg}'],
  swDest: 'dist/sw.js',
  runtimeCaching: [{
    urlPattern: /^https:\/\/api\./,
    handler: 'NetworkFirst',
  }],
}
```

Build:

```bash theme={null}
npx workbox generateSW workbox-config.js
```

## PWA Manifest

```json theme={null}
// public/manifest.json
{
  "name": "My Mizu App",
  "short_name": "MizuApp",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [
    {
      "src": "/icon-192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/icon-512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}
```

```html theme={null}
<!-- index.html -->
<link rel="manifest" href="/manifest.json">
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Production" href="/frontend/production" icon="rocket">
    Production optimization
  </Card>

  <Card title="Workbox" href="https://developers.google.com/web/tools/workbox" icon="external-link">
    Workbox documentation
  </Card>
</CardGroup>
