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.

241 lines (178 loc) • 9.77 kB
# Offline > Knowing when the server cannot be reached, and carrying on without it. `useOffline()` tells a component when the server can't be reached. Show a banner with it: ```tsx title="src/components/ConnectionBanner.tsx" 'use client' import { useOffline } from '@rsc-kit/core/useOnline' export function ConnectionBanner() { const offline = useOffline() if (!offline) return null return <p role="status">You are offline. Changes will not be saved.</p> } ``` To keep the app working with no network at all, turn on the service worker with `rscKit({ offline: true })`. ## Showing that the app is offline `useOffline()` is `true` when the router's last request failed to reach the server. `useOnline()` is the same reading the other way round: ```tsx 'use client'; import { useOnline } from '@rsc-kit/core/useOnline'; export function Status() { return <span>{useOnline() ? 'connected' : 'reconnecting…'}</span>; } ``` Both read one store, so they never disagree. ### What "offline" means here It is whether the router could reach the server on its last attempt, not `navigator.onLine`. A laptop on café wifi that needs a login is "online" to `navigator.onLine` and can reach nothing. The router reports what it actually saw, which is what a person means by offline. So the value only changes when something is tried. A tab sitting idle on a dead connection reports online until the next navigation, prefetch or action fails. ### When a link can't reach the server A navigation that gets no answer at all does one of two things, depending on what the browser says about its own connection: - **The browser is offline** (`navigator.onLine` is `false`): the page stays as it was, `useOnline()` turns `false`, and an `rsc-navigate-error` event is dispatched on `window` with the url. Nothing is lost from the screen. - **The browser is online**: the server is down, not the connection - a stopped dev server, a deploy that is restarting. The url is loaded as a document, as a plain link would be, and the browser shows its own error page. A click that did nothing would look like a broken link. A server that answers with an error is neither: the page's error boundary shows it. ### During a server render `useOffline()` returns `false` on the server, and `useOnline()` returns `true`. The server can reach itself, and any other answer would render an offline state into the HTML that the browser then disagreed with on hydration. ## Working with no network at all Turn on the service worker in the plugin options. It is off by default: ```ts title="vite.config.ts" rscKit({ offline: true }) ``` The build writes `sw.js` beside the assets, and the generated entry registers it once the page has loaded. With it on, a page you have visited survives a full reload with no network, and comes back interactive. Without it, everything lives in one page's memory: the pages a boundary keeps mounted, and the prefetch cache. A reload with no network shows the browser's own error page, because no script runs. A service worker is the only thing that survives that. The first visit still needs a reload. A worker doesn't control the page that registered it, so the first visit caches what it needs, and the *second* is the one that survives being offline. That is how service workers work everywhere. ### What is cached, and when | | | | --- | --- | | what boots the app | at install: the scripts, stylesheets, fonts, manifest and icons, plus `/` and the offline page with the payloads they boot from | | images, wasm, the share card | the first time they are used, so an install costs what a first page costs | | any other hashed asset | the first time it is asked for, then from the cache forever — the name changes when the bytes do | | a page you loaded | its document, and the payload it boots from | | a page you reached by link | its payload, and its document fetched once to go with it | | a page you never visited | nothing | A hard load fetches a document and never the payload; a link fetches a payload and never the document. Either alone is half a page, so whichever arrives first fetches the other, **once per url**. A page costs one extra request the first time you reach it, and none after. A url you have never opened can't be served offline, and isn't faked with another page. Add an [offline page](#showing-a-page-when-nothing-can-answer) for those. ### Keeping private data out of the cache Anything the server sent with `Cache-Control: no-store` is never cached. The Cache API files responses by url and knows nothing about who asked, so a guarded page, or a [query](/guides/queries/) that read the session, would be handed to whoever opens the app next on that machine. That is why a query doesn't work offline by default: queries answer `private, no-store`, because they may read the session. Widen one only when the answer is the same for everyone: ```ts title="src/queries/pricing.ts" // Cacheable, and offline, because every visitor sees the same tiers. export const getPricing = query(async () => tiers(), { cache: "private", maxAge: 300 }) ``` For a personal read you want across reloads, persist your cache library instead of widening the query. TanStack's `persistQueryClient` writes to storage that belongs to that browser, so one visitor's data is never served to the next. ### While developing Nothing of it runs in development. A worker is registered per origin, and one a production run left on `localhost:3000` would sit in front of the dev server on the same port and serve yesterday's pages. The dev server answers `/sw.js` with a worker that removes the old one and its caches, then reloads the pages it held. The browser asks for that file on every navigation, so the cleanup happens on the first load. ### Turning it off Remove `offline` and deploy. A browser that visited while it was on still has the worker, and keeps asking for `/sw.js`, so a build without `offline` writes a worker there that deletes the caches, unregisters itself and reloads the pages it held. Your own `public/sw.js`, if you have one, is left as it is. ## Showing a page when nothing can answer Add a route at `/offline`. A navigation the worker can't answer, such as a page this browser never visited, is served that page instead: ```tsx title="src/app/offline/page.tsx" export default function Offline() { return ( <main> <h1>You are offline</h1> <p>Try again once you are back.</p> </main> ) } ``` It is an ordinary route. It becomes the fallback because the build stored it and the worker precached it. **It has to be static.** A page rendered per request can't be served with no network, so the build checks and says so: ```text [rsc-kit] offline: /offline cannot be the fallback, because it called cookies(), headers(). A fallback has to be servable with no network at all. ``` It is served for navigations only. A payload request answered with a document would reach the Flight decoder, which throws. ## Telling visitors a new version is live A new worker takes over as soon as it installs and sweeps the previous build's cache. A page left open across a deploy keeps running, but the chunks it hasn't loaded yet are gone. `useAppUpdate()` says when that happened: ```tsx title="src/components/UpdateBanner.tsx" 'use client' import { useAppUpdate } from '@rsc-kit/core/useAppUpdate' export function UpdateBanner() { const { updated, reload } = useAppUpdate() if (!updated) return null return <button onClick={reload}>A new version is ready — reload</button> } ``` Put it in the root layout beside the connection banner. The reload is left to the visitor, because reloading out from under someone mid-form is worse than the staleness it fixes. You don't need it for navigation to keep working. Once the worker has said a newer build is live, the next navigation is a document load from the new build. ## How it works - **Versions.** The worker's version is a hash of everything it serves cache-first: the precached files and the pages the build stored. A build that changed nothing keeps the same version and leaves a visitor's cache alone. A build that changed anything, a stored page included, is a new worker, which sweeps the old caches. There is no version to set, and no way to strand someone on a stale worker. An app that writes the build time into a stored page gets a new worker on every deploy, because its pages really differ. - **Taking over at once.** A new worker doesn't wait for every tab to close. That is safe because assets are addressed by content: a page already open goes on asking for the names it was built with. - **A page from the previous build.** Every document says which build it is, and the client says it back on every navigation. A server on another build answers `409`, and the client loads the document instead. Under a worker this is every returning visitor's first navigation after a deploy, because the worker serves the previous build's document from its cache while the new one installs. Without it, that navigation ended on the route's error boundary with "client reference not found". - **Why there is no fallback to `/`.** Answering an unknown url with the cached home page was tried. The document *is* the page here, so the visitor got the home page's markup under the address they asked for, and it didn't hydrate. <Aside type="caution" title="It can hide a server that is down"> Serving from a cache asks nothing of the network, so an app can look healthy while its backend is not. With the worker on, show `useOffline()` in the interface. </Aside> Installing, push notifications and background sync are in [Progressive web apps](/guides/pwa/).