The store, persistence and the offline queue keep a page working once it has loaded, also while the live connection is down. Opening a page with no network at all takes two more pieces, both optional:

  • a service worker (live_slice/sw) that keeps the pages, the static files and the data responses an app lists, and serves them when the network fails;
  • the offline mount (live_slice/offline), which runs the hooks an app marks as safe without a server against that page. LiveView mounts hooks only after the LiveView joined, so without it no hook would run and the client stores would have nothing to draw into.

An app that registers neither behaves exactly as before. Service workers need a secure context: https, or localhost in development.

What the worker keeps

RequestsStrategy
Same-origin GET navigations (pages)Network first, for networkTimeout ms (3000 by default); then the copy kept for that URL, then the offlinePage if configured, then the browser's error page. A 502, 503 or 504 answer counts as no answer: the kept copy, then the offlinePage, then that answer. Without a kept copy, a slow network is waited for. A late answer still refreshes the copy.
Static files: /assets/ (the static patterns) and the precache listCache first, ignoring the query string (?vsn=d). A file whose name carries a mix phx.digest digest is never fetched again; any other one is refreshed in the background, so the next load gets the new copy.
The data allow-listPer rule: "network-first" (the default), "cache-first" (for URLs that carry their own version) or "stale-while-revalidate", keyed by the full URL.
Everything else: other methods, other origins, Range requests, /live and /phoenix (the LiveView socket), the exclude patterns, unlisted URLsPassed through untouched, never cached.

Patterns are strings, which match that path and everything below it ("/api/logs" matches /api/logs and /api/logs/2, not /api/logsets), or regular expressions, tested against the path and query string.

Only complete answers are kept: status 200, same origin, not the end of a redirect, without Cache-Control: no-store; for a navigation, also only text/html without Content-Disposition: attachment, so a CSV export, a PDF or a JSON document opened in a tab is passed on and never kept as a page. A redirect (to a login page, say) is passed on and never kept as the page that redirected, and a navigation answered with a redirect, 401, 403, 404 or 410 drops the copy kept for that URL; a server error (5xx) keeps it. A 502, 503 or 504 (a proxy answering while the app restarts, an overloaded server) is treated like a failed network, so the kept copy is served; a 500 is the page's own error and is passed on, since a kept copy would hide it and its LiveView would most likely fail to join the same way. maxPages (50) and maxDataEntries (200) bound the kept pages and data, oldest written first out. A Cache Storage that fails (a full quota, a private window, a broken browser profile) holds nothing and keeps nothing: every request goes to the network, as without the worker.

The offlinePage is fetched at install without cookies, so it holds nothing of the signed-in user: it must be reachable without a session (a static file such as /offline.html, or a route outside the authenticated pipeline). It is kept with the static files of the version, so neither maxPages nor clearUserCaches() removes it. The pages are fetched with the user's session and kept in the pages cache, which clearUserCaches() empties: after a sign-out they are kept again as they are visited. They are fetched without following redirects: a page the server redirects (to the sign-in page, while nobody is signed in) is skipped, and the page the redirect points to is not requested, so its answer cannot replace the session cookie of the page that is open.

The caches are live_slice:<version>:static, live_slice:<version>:pages and live_slice:data, plus live_slice:meta, which holds the generation (see Signing out), the install order of the versions, their install reports and the active version. Installing records a generation if there is none and takes the next place in the install order, notes the generation for the pages, then precaches the static files (see Install failures for one that cannot be fetched), the offlinePage and the listed pages (both best effort); the pages are kept only if the generation did not change since the install began. Activating deletes the static and pages caches (and install reports) of the versions installed before it, records itself as the active version and takes control of the open pages; the caches of a version that began installing after it are left alone, since it may still be installing, and that version deletes the older ones when it activates. Versions are opaque strings, so the order is the install order. The data cache is shared by every version: data URLs carry their own version, as chunk URLs do.

Setup

  1. The worker is a few lines of the app's own:

    // assets/js/sw.js
    import { installServiceWorker } from "live_slice/sw";
    
    installServiceWorker(self, {
      ...self.LIVE_SLICE_SW, // {version, precache}, written in front of the script by LiveSlice.ServiceWorker
      pages: ["/", "/tasks"], // kept at install, so they open offline before a visit; others when visited
      data: [/^\/api\/logs\?/, { match: "/api/tiles", strategy: "cache-first" }],
      // also: networkTimeout, maxPages, maxDataEntries, offlinePage, exclude, static, essential, immediate
    });

    Requests it does not handle get no respondWith, so a fetch listener added after it can answer them.

  2. Bundle it on its own, since a worker cannot share app.js. In config/config.exs, next to the app's profile:

    config :esbuild,
      service_worker: [
        args: ~w(js/sw.js --bundle --target=es2022 --outdir=../priv/static/assets/js),
        cd: Path.expand("../assets", __DIR__),
        env: %{"NODE_PATH" => [Path.expand("../deps", __DIR__), Mix.Project.build_path()]}
      ]

    Add "esbuild service_worker" to the assets.build alias, "esbuild service_worker --minify" to assets.deploy (before phx.digest), and a watcher in config/dev.exs if you work on it.

  3. Serve it from the root of the site, before Plug.Static in the endpoint, with the same :only and :only_matching filters as Plug.Static (or narrower ones):

    plug LiveSlice.ServiceWorker,
      at: "/sw.js",
      from: :my_app,
      script: "assets/js/sw.js",
      only: ~w(assets fonts images favicon.ico),
      only_matching: ~w(favicon)
    
    plug Plug.Static,
      at: "/",
      from: :my_app,
      gzip: not code_reloading?,
      only: MyAppWeb.static_paths(), # ~w(assets fonts images favicon.ico robots.txt)
      only_matching: ~w(favicon)

    The plug answers GET and HEAD of /sw.js with Cache-Control: no-cache, and writes self.LIVE_SLICE_SW = {"version": ..., "precache": [...]} in front of the bundle. LiveSlice.ServiceWorker.manifest/2 computes both: after mix phx.digest, from cache_manifest.json (both names of each file, the digested one that pages ask for and the plain one that code may ask for, such as a worker script or a lazily loaded chunk; versioned by the digests); without it, from the files of the static directory, versioned by their paths, sizes and modification times. Source maps and gzip copies are left out. A new asset build thus changes the served bytes, which is how the browser notices a new version. Served below the root (say at: "/assets/sw.js"), the answer adds Service-Worker-Allowed: /. Before the bundle exists, /sw.js answers 404.

    Which paths the endpoint must serve. The worker fetches every URL of the precache list when it installs, so each one must answer 200 through the endpoint, without a session. A URL is listed only when Plug.Static with the same filters serves it: its first path segment is one of :only, or starts with one of :only_matching. After mix phx.digest, a file at the top of the static directory has two names, favicon.ico and favicon-<digest>.ico, and pages that use ~p"/favicon.ico" ask for the digested one. only: ~w(favicon.ico) matches only the plain name; only_matching: ~w(favicon) matches both. The plug leaves out a name the filters do not serve and logs that once per version with Logger.warning, naming the file and the :only_matching entry that would serve it. With different filters on the two plugs, Plug.Static may answer 404 for a listed URL (see Install failures). A test in the app keeps them in step:

    test "the endpoint serves every URL the service worker precaches", %{conn: conn} do
      static = Application.app_dir(:my_app, "priv/static")
      filters = [only: ~w(assets fonts images favicon.ico), only_matching: ~w(favicon)]
      %{precache: urls} = LiveSlice.ServiceWorker.manifest(static, [except: ["assets/js/sw.js"]] ++ filters)
    
      for url <- urls, do: assert(get(recycle(conn), url).status == 200, "#{url} is not served")
    end

    Run it after mix assets.deploy (or mix phx.digest) to cover the digested names; the demo keeps the filters in DemoWeb.precached_static/0 and has this test.

    The worker's own file. The plug leaves its :script out of the list it serves (except: [script]), in development and after mix phx.digest alike: the browser fetches the worker itself, never from the precache. manifest/2 called directly lists it unless :except names it, and then differently per build: after mix phx.digest under both names (/assets/js/sw.js and /assets/js/sw-<digest>.js, since phx.digest digests the worker bundle like any other file), in development under its plain name only. So pass except: ["assets/js/sw.js"] (the plug's :script) in a test that compares the list with what the endpoint serves, as above, or the two builds disagree.

  4. Register it from app.js, behind a flag the server sets (the demo renders it in a meta tag):

    import { registerServiceWorker, unregisterServiceWorker } from "live_slice/offline";
    
    registerServiceWorker({
      url: "/sw.js",
      enabled: document.querySelector("meta[name='service-worker']")?.content === "enabled",
      onUpdateReady: (activate) => showUpdateNotice(activate), // see Updates below
      onControllerChange: () => window.location.reload(),
      onInstallFailed: ({ version, failures }) => showNotice(`Offline use is not available (${failures.length} files)`),
    });

    enabled has no default, on purpose: each app decides, typically on in production and off in development. With false, the worker registered from url and the live_slice caches are removed instead. Registering waits for the page's load event, and resolves to the registration (or null). onInstallFailed is optional; see Install failures.

  5. Mount the offline-safe hooks before connecting:

    import { createOfflineMount } from "live_slice/offline";
    
    const offline = createOfflineMount({
      hooks: { LiveSlice: LiveSliceHook, TaskList, TaskForm, TaskStatus },
      // also: mountAll, exclude, timeout (3000), attribute ("data-live-slice-offline"), onChange(active),
      // bindingPrefix
    });
    const liveSocket = new LiveSocket("/live", Socket, {
      params: { _csrf_token: csrfToken },
      hooks: { ...otherHooks, ...offline.hooks },
    });
    offline.start(liveSocket);
    liveSocket.connect();

    longPollFallbackMs. The app.js that Phoenix generates passes longPollFallbackMs: 2500 to LiveSocket. A page started offline fails its WebSocket at once, so Phoenix falls back to long polling, and when that connects later (the network is back) it remembers the choice in sessionStorage (phx:fallback:LongPoll): every page of that tab then uses long polling until the tab is closed, with a request per message and more latency. live_slice works over either transport. For an application that starts offline, leave longPollFallbackMs out (WebSocket only, which reconnects on its own) unless its users sit behind proxies that block WebSockets; if you keep it, sessionStorage.removeItem("phx:fallback:LongPoll") before liveSocket.connect() gives each page load a new chance at the WebSocket.

Install failures

The install tries every URL of the precache list and decides by kind:

  • Essential files fail the install. By default these are scripts, stylesheets and WebAssembly (.js, .mjs, .css, .wasm): a kept page does not run without them. The version is then not installed; an earlier version that is active keeps serving with its own files, and without one nothing opens offline.
  • Other files are skipped. An icon, an image, a font or a text file that cannot be fetched is left out, and the install goes on; such a file is fetched from the network when a page asks for it, like a file that was never precached.
  • The offlinePage and the pages never fail the install. Pages are fetched with the user's session, and a visitor who is not signed in gets redirects. A redirected page is not followed: it is skipped and listed in the report, without a warning (see below).

essential in the worker's options changes the rule: a list of patterns (strings or regular expressions, as for static) of the precache URLs that fail the install. essential: ["/"] makes every file essential (the behaviour before this option existed), essential: [] none.

Either way, the install ends with a report: console.error (failed) or console.warn (files skipped) in the worker, a message {type: "live_slice:install", version, ok, failures} posted to every page of the origin, controlled or not, and a record in live_slice:meta. Each failure is {url, kind, essential, status, error?}: kind is "static", "offlinePage" or "page", status the HTTP status (null when the request itself failed, and for a redirected page, since a redirect that is not followed hides its status), and error what else was wrong ("redirected", a network error's message). registerServiceWorker logs a failed install with console.error in the page, naming each URL and its status, and calls onInstallFailed({version, failures}); skipped files are logged with console.warn. Pages skipped because they were redirected are left out of the warning, in the worker and in the page: a first visit on a device usually lands on the sign-in page, where every listed page redirects, so only the report lists them. When other files were skipped too, the warning names only those.

A page can ask whether this device opens it offline now:

import { offlineReadiness } from "live_slice/offline";

// A promise, not a top-level await: Phoenix's esbuild config bundles app.js as a script (iife), where
// esbuild refuses top-level await (and targets before es2022 have none).
offlineReadiness().then(({ ready, reason, missing }) => {
  // or offlineReadiness({ pages: ["/", "/tasks"] })
  if (!ready) showNotice(`Not available offline yet (${reason})`);
});

It reads the caches rather than trusting the registration: ready is true when a worker is active for the page, the essential files of its version are still in the Cache Storage (a browser may evict them) and so are the pages asked about (the current page by default). Otherwise reason says why: "unsupported" (no service worker or Cache API), "not_registered", "installing", "install_failed" (no worker is active and the last install failed; failures lists why), "no_record" (the active worker is from a live_slice without install reports), "missing_files" or "missing_pages" (missing lists them). version is the active version. The offlinePage counts among the files when its install kept it (with its query string, as the worker keeps it); one the server refused is best effort and not required. An update whose install failed leaves the active version ready and lists its failures; "after" is the worker's install order, not the clock, so two installs in the same millisecond or a clock that moved back do not hide it.

The offline mount

createOfflineMount({ hooks }) returns { hooks, start, stop, active }. Register its hooks with the LiveSocket in place of the ones you listed.

  • Which hooks. Only hooks that work from client stores and the DOM they own, without a server: they read and write stores, draw under phx-update="ignore", fetch same-origin data the worker keeps. Include the LiveSlice bridge. Object hooks only: a hook class (a ViewHook subclass) cannot be built without LiveView.

  • Every hook at once. When nearly every hook of the app works offline, pass them all with mountAll: true instead of listing them, and name the ones that need the server in exclude:

    const offline = createOfflineMount({
      hooks: { ...colocatedHooks, ...libraryHooks, LiveSlice: LiveSliceHook, TaskList, Chart },
      mountAll: true, // every object hook mounts offline; hook classes pass through to LiveView
      exclude: ["Chart"], // needs the server
    });
    const liveSocket = new LiveSocket("/live", Socket, { hooks: offline.hooks });

    offline.hooks then holds every hook given: the ones mounted offline wrapped for the handover, the others unchanged.

  • Hooks that do not run. When the hooks mount, an element of the page whose hook is not mounted offline (not listed, or a hook class) is reported with console.warn, once per hook name, naming the hook and the element: the hook "Chart" of #sales-chart does not run while the page is offline. LiveView's own hooks (names starting with Phoenix., such as Phoenix.LiveFileUpload and Phoenix.FocusWrap) are never reported. Name a hook that rightly needs the server in exclude to silence it.

  • When. start(liveSocket) watches, on a page with a LiveView, until it joined. The hooks mount at once if navigator.onLine is false, or as soon as the browser goes offline, the socket reports an error (liveSocket.getSocket().onError), or timeout ms pass without a join. Each element whose phx-hook (or data-phx-hook) names a listed hook gets an instance, in document order, unless LiveView already mounted that hook on it (a hook outside the LiveView mounts without a server).

  • The instance. A copy of the hook object, as LiveView makes, with el, liveSocket and offline: true. pushEvent and pushEventTo reject with an offline error (given a reply callback, they do nothing, as LiveView does while disconnected), handleEvent registers nothing, upload throws, and js() returns the LiveSocket's public js() commands plus exec. The bridge starts disconnected: a persisted store hydrates, DOM bindings apply, server actions queue, and no attempt is counted.

  • Handover. When LiveView mounts a listed hook, the offline instance on the same element is destroyed first (its destroyed() runs), in the same task, so nothing renders twice and no listener leaks. When the main LiveView joined (phx:page-loading-stop with kind "initial"), the instances left are destroyed, last mounted first, and the offline mount stops for good: a later disconnect is LiveView's ordinary disconnected().

  • What the user sees. The page is the server's render from when the worker kept it, with the hooks drawing the current client state into it. Server-rendered parts (a table, a count) are as old as the copy, and elements under phx-update="ignore" keep what the offline instance drew until LiveView's instance draws again. While offline instances run, the root element carries data-live-slice-offline (the attribute option), and onChange(true) / onChange(false) report it, so the app can say that it shows saved data:

    #offline-banner { display: none; }
    [data-live-slice-offline] #offline-banner { display: block; }

    Write offline-safe hooks so they can be mounted, destroyed and mounted again on the same element, and draw from the store rather than from server-rendered content. A hook can check this.offline, for example to keep a control that needs the server disabled.

Updates

A new version (a new asset build) installs in the background and waits until no page uses the old one, so a page never mixes the assets of two versions. registerServiceWorker calls onUpdateReady(activate) when one waits, also for one that was already waiting or still installing when the page registered; activate() lets it take over, and onControllerChange() then fires in every page it took over, which typically reloads. It does not fire for the first worker, which takes control of the page that registered it without a reload.

With immediate: true in the worker, a new version takes over as soon as it is installed: no prompt, but a page loaded with the old assets keeps running while the caches it may still need (a lazily loaded file, a page it navigates to) are replaced. onUpdateReady may still fire just before; activate() is then harmless.

Signing out

Kept pages carry the user's data and the CSRF token and LiveView session of their session. Browsers do not show service workers the Set-Cookie header, so the worker cannot tell private answers apart by their headers: it keeps only pages, static files and the data the app listed. On sign-out, before the request:

import { clearUserCaches } from "live_slice/offline";
import { removeStore } from "live_slice";

await clearUserCaches(); // the kept pages and data of every version; the static files stay
await removeStore("tasks", { clearPersisted: true }); // and each persisted store (see Known limits)

A page the server answers with a redirect, 401 or 403 after sign-out is dropped from the cache anyway, but only once it is visited; clearUserCaches() drops them all.

Requests may still be in flight at that moment: a navigation whose late answer refreshes the kept copy, a "stale-while-revalidate" refresh, an install precaching pages. None of them writes the user's answer back. clearUserCaches() first records a new generation in the live_slice:meta cache; the worker notes the generation before each request whose answer it may keep goes out (an install notes it once, when it begins, for all its pages), and keeps the answer only if the generation did not change, through the cache it opened then (the Cache API's open would otherwise create a deleted cache again). The record lives in the Cache storage, so it holds when the browser stops and restarts the worker, and clearUserCaches() works from any page of the origin, with or without a worker in control. unregisterServiceWorker({ clearCaches: true }), and registerServiceWorker({ enabled: false }), first record that there is no generation (a "none" marker in live_slice:meta, which they do not delete, holding a token of that reset), then delete the other caches: a worker still in control of an open page keeps nothing from then on, until a new install records a new generation and then records that reset's token as lifted. The marker is never removed: a reset that lands while an install lifts an earlier one writes a new token, which stays in force. clearUserCaches() never lifts a reset, so a sign-out in one tab cannot undo a reset in another, whatever order their steps run in. In a browser where no worker ever recorded a generation, neither creates live_slice:meta.

What remains: a request that begins after clearUserCaches() and before the sign-out request has changed the session cookie still carries the old session, and its answer is kept. Call clearUserCaches() right before the sign-out request, not earlier. After it, pages are kept again as they are visited, with the new session.

Development

Keep the worker off in development: kept pages and assets hide changes until it updates, and files without a digest are served from the cache and refreshed in the background, so a page is one load behind. With the flag off, registerServiceWorker({ enabled: false }) removes a worker an earlier page registered, with its caches; the reload after that gets a page without one. To reset by hand from the console (the demo exposes this as resetServiceWorker()):

await unregisterServiceWorker({ url: "/sw.js", clearCaches: true }); location.reload();

unregisterServiceWorker({ url, clearCaches }) resolves to {unregistered, deletedCaches} (live_slice:meta stays, with the record that there is no generation); without url, it removes every service worker of the origin. The page stays controlled until it unloads, hence the reload; until then the old worker still answers from the network, but keeps nothing (see Signing out).

What stays with LiveView

Read in the sources of LiveView 1.2.15 and Phoenix 1.8; these are internals and may change in a later release.

  • A kept page joins with old tokens. It carries the CSRF token (the _csrf_token connect param) and the signed LiveView session (data-phx-session) of when it was kept. If the session cookie still holds the same CSRF state and the session token is less than two weeks old (@max_session_age in phoenix_live_view/static.ex), the join succeeds and nothing reloads: the join patch replaces the server-rendered parts. Otherwise the socket connects without a session (csrf_token_valid? in Phoenix's socket/transport.ex), LiveView refuses the join with "stale" or "unauthorized" (mount/3 in phoenix_live_view/channel.ex), and the client navigates to the same URL (onJoinError in view.ts, through liveSocket.redirect). The worker sends that navigation to the network first, so it gets a fresh page that joins: one reload. If the network is slower than networkTimeout at that moment, the old copy is served once more while the late answer replaces it, so the next join gets the fresh page: the repeat lasts only while the network stays that slow.
  • Stale-page recovery covers LiveView pages only. What replaces a kept page with a fresh one is the LiveView join just described. A page without a LiveView has no join: a kept copy served because the network failed or was slower than networkTimeout stays on screen as old as the copy, and nothing reloads it (the late answer refreshes the kept copy, so the next load is fresh). This matters for plain forms posted to a controller, such as a sign-in or a settings form: the form carries the CSRF token (_csrf_token) of when the page was kept, and if the session changed since (a sign-in, a sign-out, an expired cookie), Phoenix refuses the post (Plug.CSRFProtection.InvalidCSRFTokenError, a 403). List such pages in exclude, so they always come from the network (and are not kept for offline use), or render the form in a LiveView.
  • Push timeouts reload. A push that gets no reply within 30 seconds while its LiveView did not rejoin makes LiveView disconnect and reload the page 5 to 10 seconds later (pushWithReply in view.ts, reloadWithJitter in live_socket.ts). With the worker, that reload gets the kept copy when the network is down or slower than networkTimeout, and the offline mount runs the hooks: the page stays usable, and the persisted queue sends the action again (same id, next attempt) once the server answers. LiveView counts consecutive reloads per path in localStorage (after ten, the next ones wait 30 seconds instead) and clears the count on a successful join (onJoin in view.ts); a page that cannot join does not reload by itself (onJoinError reloads only while the socket is connected), so the count does not grow while offline.
  • No server. While the socket cannot connect, LiveView puts its loading and error classes on the page and runs the phx-disconnected bindings (onError and displayError in view.ts), which in the default Phoenix layout show a "We can't find the internet" or "Something went wrong" notice; the demo hides both under [data-live-slice-offline] in favor of its own banner.
  • Detection. The offline mount finds LiveView pages by [data-phx-session], the selector LiveView joins (PHX_VIEW_SELECTOR in constants.ts), and the join by the phx:page-loading-stop event with kind "initial", dispatched after the join patch and its hooks (applyJoinPatch in view.ts).