UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

530 lines (410 loc) • 18.6 kB
# Progressive web apps > Making the app installable, and adding push notifications and background sync. An installable app is a manifest and a service worker. The manifest is a file beside your routes: ```ts title="src/app/manifest.ts" import type { WebManifest } from '@rsc-kit/core/manifest-file' export default { id: '/', name: 'Orders', shortName: 'Orders', themeColor: '#0b0b0c', backgroundColor: '#ffffff', } satisfies WebManifest ``` Put `icon-192.png` and `icon-512.png` next to it, turn on `offline`, and the browser offers to install the app. [Offline](/guides/offline/) covers the service worker. This page covers the rest: the manifest, an install button, splash screens, push notifications and background sync. ## Starting one installable ```sh bun create rsc-kit@latest my-app --pwa ``` Or answer yes to *Installable app* when it asks. It turns on `offline` and writes: - `src/app/manifest.ts` - a static `/offline` page - four starter icons: `icon-192.png`, `icon-512.png`, `icon-maskable-512.png` and `apple-icon.png` The app is installable as soon as it exists. Chrome's installability check finds nothing missing, and with the network cut the home page still loads and a page never visited lands on `/offline`. Replace the icons with your own and keep the names. It is off by default. A service worker outlives the code that installed it, so take it on deliberately. ## Declaring the manifest `src/app/manifest.ts` exports an object literal. The build reads it, writes `manifest.webmanifest`, and links it from every page: ```ts title="src/app/manifest.ts" import type { WebManifest } from '@rsc-kit/core/manifest-file' export default { id: '/', name: 'Orders', shortName: 'Orders', description: 'Track and ship orders.', startUrl: '/orders', themeColor: '#0b0b0c', backgroundColor: '#ffffff', shortcuts: [ { name: 'New order', shortName: 'New', url: '/orders/new', icons: ['icon-96.png'] }, ], } satisfies WebManifest ``` There is no layout to edit. React hoists the `<link>` and the `theme-color` meta into `<head>`, so this works in an app with its own root layout. **Set `id` once and never change it.** It is the app's identity. Without it a browser derives one from `startUrl`, and changing that later leaves everyone who installed with an app their device no longer recognises as yours. `'/'` is right for almost everyone. The file must be an object literal. It is read before there is a module graph, so a computed or imported value is a build error rather than an app that is quietly not installable. ### The fields | Field | What it does | | --- | --- | | `id` | The app's identity. Set it to `'/'`. | | `name`, `shortName`, `description` | What the install sheet and the home screen show. | | `startUrl` | Where a launch lands. Defaults to `/`. | | `scope` | The URLs that are the app. A link outside it opens in the browser. | | `display` | `standalone` (the default), `fullscreen`, `minimal-ui` or `browser`. | | `orientation` | Lock the installed app to portrait or landscape. | | `categories` | What a store files it under, such as `['productivity']`. | | `shortcuts` | The jumps a long press on the icon offers. | | `themeColor` | The colour of the browser's chrome. Also written as a meta tag. | | `backgroundColor` | The colour behind the app while it starts. | | `icons`, `screenshots` | Usually left out: they are found by name. | | `other` | Anything else the spec allows, passed through as written. | ### Icons Put the icons next to `manifest.ts`. They are found by name, and their sizes are read from the name: ```text src/app/ manifest.ts icon-192.png any, 192px icon-512.png any, 512px icon-maskable-512.png maskable, 512px apple-icon.png the iOS home screen icon ``` `icon-192.png` and `icon-192x192.png` both mean 192. A file named `icon-maskable-*.png` is `maskable`. Draw it with a safe zone, since a launcher only promises to show the middle 80%, and Android can mask it to its own shape without cutting anything off. It goes in the manifest and never in `<head>`, where the padding would make it the small icon in the tab. To keep icons in `public/` instead, list them in `icons` as paths there: `icons: ['icon-192.png', 'icon-512.png']`. A listed set replaces the files found by name. ### What the build warns about A manifest with no icons is valid. It parses, it links, and no browser ever offers to install it. So the build says what is missing: ```text [rsc-kit] manifest: no icons, so no browser will offer to install this. Add a 192px and a 512px png. [rsc-kit] manifest: no 512px icon, so a splash screen will be upscaled from a smaller one. [rsc-kit] manifest: no backgroundColor, so the Android splash screen is white. [rsc-kit] manifest: no id, so the app's identity is its startUrl - change that and everyone who installed has a different app. [rsc-kit] manifest: Orders is installable ``` These are warnings, not a failed build. The manifest still sets the theme colour and the name. ## Adding an install button `useInstall()` says whether the browser has offered to install the app, and shows its dialog: ```tsx title="src/components/InstallButton.tsx" 'use client' import { useInstall } from '@rsc-kit/core/install' export function InstallButton() { const { canInstall, install, installed, ios } = useInstall() if (installed) return null if (canInstall) return <button onClick={install}>Install</button> if (ios) return <p>Tap Share, then Add to Home Screen.</p> return null } ``` - **`canInstall`**: the browser has offered. `install()` shows its dialog and resolves with `accepted` or `dismissed`. An offer can be shown once, so after that it resolves with `unavailable` until the browser makes another. - **`ios`**: Safari on an iPhone or iPad. iOS makes no offer, and the visitor installs from the Share menu. The most the app can do is say so. - **`installed`**: running as the installed app, or installed while this page was open. Use it to hide the button, or for anything that should differ in the app's own window. To act on what the visitor chose: ```tsx async function onInstall() { const outcome = await install() if (outcome === 'accepted') track('installed') } ``` The browser's own install UI is left alone, so an app with no button loses nothing. ## Showing screenshots in the install sheet Chrome shows a plain install dialog by default, and a fuller one, like an app store listing, when the manifest has screenshots. Name the files by their size: ```text src/app/ screenshot-wide-1280x720.png desktop screenshot-narrow-750x1334.png a phone ``` Each becomes a manifest `screenshots` entry with its `sizes` and a `form_factor` of `wide` or `narrow`. Chrome wants at least one wide screenshot for the desktop sheet and one narrow one for a phone. The build mentions them when an otherwise installable app has none. ## Splash screens What shows while an installed app starts. Android and iOS do it differently, and neither needs anything run over your images. You make them, and the build links them. ### Android Chrome and Edge draw the splash from three things the manifest already has: the `name`, the largest icon and `backgroundColor`. Give it a 512px icon and a background colour and it is done. ### iOS Safari ignores the manifest for this. It wants one image per device and orientation, each behind a media query naming the device's size and pixel ratio, and with no match it shows a blank screen. Name each image by its size and the build writes the query: ```text src/app/ apple-splash-1179x2556.png iPhone 14 Pro, 15, 15 Pro, 16, portrait apple-splash-2556x1179.png the same phones, landscape apple-splash-1290x2796.png iPhone 14 Pro Max, 15 Plus, 15 Pro Max, 16 Plus ``` Each becomes `<link rel="apple-touch-startup-image" media="…">` with the right query, and the page says it launches as an app, which is when Safari shows one. Make images for the devices you care about. Every other device gets the background colour. | Size (portrait) | Devices | | --- | --- | | 1320×2868 | iPhone 16 Pro Max | | 1206×2622 | iPhone 16 Pro | | 1290×2796 | iPhone 14 Pro Max, 15 Plus, 15 Pro Max, 16 Plus | | 1179×2556 | iPhone 14 Pro, 15, 15 Pro, 16 | | 1284×2778 | iPhone 12 Pro Max, 13 Pro Max, 14 Plus | | 1170×2532 | iPhone 12, 12 Pro, 13, 13 Pro, 14 | | 1242×2688 | iPhone XS Max, 11 Pro Max | | 1125×2436 | iPhone X, XS, 11 Pro, 12 mini, 13 mini | | 828×1792 | iPhone XR, 11 | | 1242×2208 | iPhone 6, 7, 8 Plus | | 750×1334 | iPhone 6, 7, 8, SE (2nd and 3rd) | | 640×1136 | iPhone SE (1st) | | 2064×2752 | iPad Pro 13" (M4) | | 2048×2732 | iPad Pro 12.9" | | 1668×2420 | iPad Pro 11" (M4) | | 1668×2388 | iPad Pro 11" | | 1640×2360 | iPad Air 10.9", iPad (10th) | | 1668×2224 | iPad Pro 10.5", iPad Air (3rd) | | 1620×2160 | iPad 10.2" | | 1488×2266 | iPad mini (6th) | | 1536×2048 | iPad mini, iPad Air, iPad 9.7" | Swap the numbers for landscape. A size no device has is served but linked from no page, and the build names it: ```text [rsc-kit] apple-splash: apple-splash-1000x2000.png matches no iPhone or iPad screen, so no page links to it. ``` ### In metadata, the way Next writes it A port from Next keeps its `appleWebApp` as it is, rendered as the same tags: ```ts title="src/app/layout.tsx" export const metadata: Metadata = { appleWebApp: { capable: true, title: 'Orders', statusBarStyle: 'black-translucent', startupImage: [{ url: '/splash-1179x2556.png', media: '(device-width: 393px) and (-webkit-device-pixel-ratio: 3)' }], }, } ``` `appleWebApp: true` is `{ capable: true }`. The files above are the easier way to supply launch screens. This is for an app that already has its queries written. ## Adding your own worker code Push, notification clicks and background sync are events the generated worker doesn't handle. Write them in `src/app/sw.js`: ```js title="src/app/sw.js" self.addEventListener('notificationclick', (event) => { event.notification.close() event.waitUntil(self.clients.openWindow(event.notification.data.url)) }) ``` The build copies it beside the generated worker and imports it first, so your listeners are registered before anything of ours answers an event. It is precached like everything else, and the build log says it was found: ```text [rsc-kit] offline: 32 files precached as rsc-kit-3d9785e4, falling back to /offline, with app/sw.js ``` There is no option for it. The file is there or it isn't. :::caution[`.js`, not `.ts`] The browser evaluates it in a worker scope with no build step in front of it, so what you write is what runs. TypeScript would not run. ::: ## Sending push notifications Push takes five steps. Everything here is the web's own Push API and the `web-push` package; the only part rsc-kit provides is `src/app/sw.js`. ### 1. Generate keys Push needs a VAPID key pair. The public half identifies your server to the browser, and the private half signs what you send: ```sh bunx web-push generate-vapid-keys # or: npx web-push generate-vapid-keys ``` If either answers `web-push: command not found`, the runner found a copy of `web-push` in the project with no command inside it, usually a half-finished install. Ask the library itself instead: ```sh node -e "console.log(require('web-push').generateVAPIDKeys())" ``` Keep the private key with your other secrets. The public one reaches the browser, so it goes in a `VITE_` variable: ```sh title=".env" VITE_VAPID_PUBLIC_KEY=BNc... VAPID_PRIVATE_KEY=3Kq... ``` ### 2. Ask, and subscribe ```tsx title="src/components/EnableNotifications.tsx" 'use client' import { saveSubscription } from '../server/push' export function EnableNotifications() { async function enable() { if (await Notification.requestPermission() !== 'granted') return const registration = await navigator.serviceWorker.ready const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: import.meta.env.VITE_VAPID_PUBLIC_KEY, }) await saveSubscription(subscription.toJSON()) } return <button onClick={enable}>Enable notifications</button> } ``` **Ask when they have a reason to say yes**, such as right after they place an order. A prompt on first load is how an app gets denied for good: the browser remembers a refusal. ### 3. Store the subscription An ordinary [server action](/guides/server-actions/): ```ts title="src/server/push.ts" 'use server' import { client } from './client' export const saveSubscription = client.input(subscriptionSchema).handler( async ({ input, ctx }) => db.pushSubscriptions.upsert(ctx.user.id, input), ) ``` Store it against a **user**, not a session. A subscription outlives the session that created it. ### 4. Send From wherever the event happens, such as a queue, a cron or a webhook: ```ts import webpush from 'web-push' webpush.setVapidDetails('mailto:you@example.com', PUBLIC_KEY, PRIVATE_KEY) for (const subscription of await db.pushSubscriptions.forUser(userId)) { try { await webpush.sendNotification(subscription, JSON.stringify({ title: 'Your order shipped', body: 'Order #42 is on its way.', url: '/orders/42', })) } catch (error) { // 404 and 410 mean the subscription is dead: the app was uninstalled, // or the browser rotated it. Delete it rather than retrying forever. if (error.statusCode === 404 || error.statusCode === 410) { await db.pushSubscriptions.remove(subscription.endpoint) } } } ``` Don't skip the last branch. Without it, a sender's list fills with dead endpoints. ### 5. Show it The worker shows the notification, and opens its URL when it is clicked: ```js title="src/app/sw.js" self.addEventListener('push', (event) => { const payload = event.data ? event.data.json() : {} event.waitUntil( self.registration.showNotification(payload.title ?? 'Update', { body: payload.body, data: { url: payload.url ?? '/' }, }), ) }) self.addEventListener('notificationclick', (event) => { event.notification.close() event.waitUntil(self.clients.openWindow(event.notification.data.url)) }) ``` ## Syncing in the background For work that must happen even if the visitor closes the tab, such as a queued message or an offline edit. Register a sync after queueing the work: ```ts const registration = await navigator.serviceWorker.ready if ('sync' in registration) await registration.sync.register('outbox') else await flushNow() ``` Then handle it in the worker: ```js title="src/app/sw.js" self.addEventListener('sync', (event) => { if (event.tag === 'outbox') event.waitUntil(flushOutbox()) }) async function flushOutbox() { const db = await openDB() for (const item of await db.getAll('outbox')) { const response = await fetch('/api/messages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(item.body), }) // Left in the queue on failure, so the browser retries the sync later. if (response.ok) await db.delete('outbox', item.id) } } ``` Only Chromium supports it; Safari and Firefox don't. Treat it as an optimisation over an ordinary retry, which is why the example falls back to `flushNow()`. :::danger[Make the endpoint idempotent] The browser decides when a sync runs and may run it more than once. A request that succeeded on the server but whose response never arrived is retried, and a message posted twice was sent twice. Give each queued item an id the client generates, and have the endpoint ignore one it has already seen. Only your data model knows what "already seen" means, so no framework can do this for you. ::: ## Moving to another domain Redirecting the old origin, such as `www.example.com` to `example.com`, needs one exception: keep serving `/sw.js` on the old origin, without a redirect. ```txt www.example.com/* → 301 https://example.com/:path www.example.com/sw.js → served by the app, as before ``` A browser never updates a worker whose script redirects. A visitor's worker on the old origin would keep answering stored pages from its cache, and never reach the redirect. With `/sw.js` still served there, the browser picks up the new worker on their next visit. From 0.42.1 the worker notices on its own when a request fails because its url now redirects. It clears its caches, unregisters, and reloads the page, so the reload reaches the redirect. A visitor whose worker is older than that needs the exception, and keep it for a few weeks so returning visitors pass through. ## How it works - **The manifest is a file, not config or metadata.** It isn't build configuration; it is something the app declares about itself, so it lives beside `layout.tsx`. It isn't `metadata` either: metadata is resolved per route and can be computed per request, while a manifest is one file for the whole app, so there is nothing to override per route. - **Icon sizes come from the filename.** Declaring a size in the config as well would be the same number written twice, and the copy that drifts is the one nobody looks at. Nothing in rsc-kit draws, resizes or encodes an image, at build, in dev or at runtime. - **The install offer is caught before the runtime.** The `beforeinstallprompt` event fires once, whenever the page qualifies, and that can be before any component's effect has run. The page's inline bootstrap catches it and `useInstall()` hands it over, so a listener in `useEffect` can't miss it. Only an app that declares a manifest has the capture. - **Splash links are cheap.** A full set of `apple-splash-*` files adds one `<link>` per image, about 4 KB before compression and well under 1 KB after. Other browsers ignore them, and iOS fetches at most the one that matches. An app with no splash files gets no tags. - **One grey frame on a dark launch.** In dark mode an installed app on iOS can show a single frame of grey (about `#2C2C2E`) between the splash and the page. iOS starts dismissing the splash one frame before the page has painted, and that frame shows the empty web view, grey in dark mode and white in light mode. Nothing in the page can reach it. It is 1/60 of a second; leave it. - **There is no push helper.** Push is the web's Push API and `web-push`. A wrapper would be a thin layer over a stable standard, so the only part rsc-kit owns is the place to put the listener, `src/app/sw.js`.