This documentation is under construction. Pages can be missing or change at any time. Follow it on GitHub.

Skip to content

Make Your App a Progressive Web App

A Progressive Web App (PWA) can be installed on the user's device and can show something useful when the network is down. Phem serves the web app manifest, the service worker and the head tags for you, with no extra PHP package. It's off by default.

Turn On the PWA#

Give your app a name and icons in phem.pwa:

# config/packages/phem.yaml
phem:
    pwa:
        name: 'Acme Notes'
        short_name: 'Notes'
        theme_color: '#4f46e5'
        background_color: '#ffffff'
        icons:
            - { src: 'images/icon-192.png', sizes: '192x192' }
            - { src: 'images/icon-512.png', sizes: '512x512' }
            - { src: 'images/icon-maskable.png', sizes: '512x512', purpose: maskable }
        offline_page: '/offline'

Phem adds two routes, so there's no routes file to import: GET /manifest.webmanifest serves the manifest built from these options, and GET /sw.js serves the service worker. Both come before your app's routes, so a catch-all page like /{slug} doesn't hide them.

Then add pwa_head() to your document's <head>:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <Head>
            <title>My app</title>
        </Head>
        {{ head() }}
        {{ theme_script() }}
        {{ pwa_head() }}
        {{ importmap('app') }}
    </head>
    <body>
        <Root>{{ children }}</Root>
    </body>
</html>

It renders the manifest link, the theme color, the Apple touch icon, and a small script that registers the service worker:

<link rel="manifest" href="/manifest.webmanifest" crossorigin="use-credentials">
<meta name="theme-color" content="#4f46e5">
<link rel="apple-touch-icon" href="/assets/images/icon-192-3f2a1c.png">
<script>(()=>{ … })()</script>

If your Content Security Policy blocks inline scripts, pass the response's nonce: {{ pwa_head(nonce: csp_nonce('script')) }} (NelmioSecurityBundle). When phem.pwa is off, pwa_head() renders nothing, so you can leave it in your document.

Give the Icons#

An icon src that isn't a URL or an absolute path is an AssetMapper logical path (images/icon-192.png in assets/), and Phem turns it into its versioned URL. Paths starting with / and full URLs stay as they are. Phem derives the type from the file extension.

Browsers need a 192x192 and a 512x512 icon to offer installation. A maskable icon fills Android's round and square shapes. iOS uses the first non-SVG icon with the any purpose.

Know the Browser's Requirements#

  • The page must be served over HTTPS. localhost is the only exception.
  • The manifest needs a name and both icon sizes.
  • The service worker must sit at the root of its scope, so keep /sw.js. A worker at /app/sw.js only controls pages under /app/.

Open the PWA Paths to All Users#

The browser fetches the manifest and the service worker with the user's cookies, so an app behind a login works. Some requests don't send cookies, though: the icons, and the offline page after the user logs out. If your firewall protects the whole app, open these paths:

# config/packages/security.yaml
security:
    access_control:
        - { path: ^/(manifest\.webmanifest|sw\.js|offline)$, roles: PUBLIC_ACCESS }
        - { path: ^/assets/, roles: PUBLIC_ACCESS }
        - { path: ^/, roles: ROLE_USER }

Show a Page When the Network Fails#

Write an ordinary page and point offline_page at it:

#[Page('/offline')]
function OfflinePage(): Node
{
    return (
        <Document title="Offline">
            <h1>You're offline</h1>
            <p>Connect to the network to load this page.</p>
        </Document>
    );
}

The service worker downloads the offline page when it installs, and shows it whenever a page load fails because of the network. Without offline_page, the browser shows its own error page.

The worker fetches the offline page again once after each start, so a deploy that changes it reaches the cache. If a path redirects (/ to /en/), the worker keeps the page at the end of the redirect.

Warning — The offline page must load without a login. If it doesn't load, the service worker doesn't install.

Keep a Copy of Each Page#

Turn on cache.pages to keep a copy of each page the user loads. When the network fails, they get the last copy, or the offline page if there's none:

phem:
    pwa:
        name: 'Acme Notes'
        offline_page: '/offline'
        cache:
            pages: true
            max_pages: 50
            precache: ['/']

The worker always tries the network first. It keeps copies of full page loads and Turbo visits, up to max_pages, dropping the oldest first. The paths in precache are cached when the worker installs.

It doesn't keep:

  • non-200 responses and redirects
  • responses that aren't HTML
  • responses with Cache-Control: no-store
  • pages that used the session, such as a logged-in user's page, unless the page has #[Page(offline: true)] (see Keep Private Data Out of the Cache)

A page with a streamed <Suspense> sends Cache-Control: no-store, private on a full load (see Know the Limits of Streaming), so only its Turbo visits, which don't stream, get a copy.

A copy holds what the response held. When the browser loads a <Suspense> with an event (a lazy boundary, a Turbo visit, or any boundary on a page with #[Cache]), the copy holds its fallback, not its content. Offline, that boundary keeps showing the fallback.

Keep Private Data Out of the Cache#

Copies stay in the browser, so on a shared computer the next person could see them while offline. Phem decides per request: when the request used the session (a logged-in user, a flash message, a CSRF token), it sends X-Phem-Pwa-Cache: no, and the worker doesn't keep the page. If it already had a copy, it removes it, so the user sees the offline page instead of an earlier visit. A no-store response leaves an older copy in place. A page that shows the toasts of a mount() redirect is never kept either, even with #[Page(offline: true)].

GET /account

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Cache-Control: max-age=0, must-revalidate, no-store, private
X-Phem-Pwa-Cache: no

This is the same rule that makes Symfony send Cache-Control: private. A session cookie alone doesn't count; the page has to read the user, through app.user, is_granted(), #[IsGranted], #[CurrentUser], or an access_control rule other than PUBLIC_ACCESS. So a page that reads no session data keeps its copy, even for a logged-in user. On the other hand, a layout that shows the user's name makes every page private.

Set offline on #[Page] to override the decision for one page:

// Keep a copy even when the request used the session.
#[Page('/notes', offline: true)]
#[IsGranted('ROLE_USER')]
function NotesPage(): Node
{
    return (
        <Document title="Notes">
            <h1>Notes</h1>
        </Document>
    );
}

// Never keep a copy, even without a session (for example, a token in the URL).
#[Page('/inbox/{token}', offline: false)]
function InboxPage(string $token): Node
{
    return (
        <Document title="Inbox">
            <h1>Inbox</h1>
        </Document>
    );
}

A #[Route] controller or a route file sets the same thing in its defaults: defaults: { _phem_offline: true }. Strings like "true" or "0" (from XML route files) are read as booleans, and any other value fails when the routes load. A page with no path gets its routes from route files, so set _phem_offline there.

To protect private pages:

  • Send Cache-Control: no-store with a private page. The worker never keeps it, even with offline: true. Phem already adds it to every page that used the session, except a page with offline: true (see Clear the History at Logout).
  • Send Clear-Site-Data: "cache", "storage" with the logout response. You need this for pages with offline: true and for the precache, whose copies otherwise stay until logout clears them.
  • Keep private data off the offline page. It's always cached, with the user's cookies. A precache path that answers with X-Phem-Pwa-Cache: no stays out of the cache.
#[Route('/logout-done')]
public function loggedOut(): Response
{
    return new RedirectResponse('/', headers: ['Clear-Site-Data' => '"cache", "storage"']);
}

"storage" removes the service worker's caches, and also the worker itself, localStorage and sessionStorage; the next page installs the worker again. "cache" clears the browser's HTTP cache.

Know What Works Offline#

A cached copy shows the page's content, but its events can't reach the server. Events in the offline queue wait for the network, just as without a worker. The worker passes these requests straight to the network:

  • Phem events (X-Phem-Event) and uploads (X-Phem-Upload)
  • every request that isn't a GET
  • the Mercure stream (text/event-stream)
  • requests to another origin or outside the scope

So retries and the offline queue behave as if there were no service worker.

Keep the Assets in the Cache#

With cache.assets (on by default), the worker serves files under cache.assets_prefix (/assets/) from its cache first. AssetMapper URLs change with the file's content, so a cached file never goes stale. The worker keeps up to 500 files and drops the least recently used ones beyond that.

Set assets_prefix to your app's framework.asset_mapper.public_prefix. Turn off cache.assets if your assets come from a CDN or have unversioned URLs.

Add an Install Button#

Enable the install controller in assets/controllers.json:

"@phem/phem": {
    "install": { "enabled": true, "fetch": "lazy" }
}

Then add a button with phem-install:

<button data-controller="phem-install" data-action="phem-install#prompt" hidden>Install the app</button>

The button stays hidden until the browser can install the app. Clicking it opens the browser's install dialog. Afterwards, and once the app is installed, it hides again. It dispatches phem-install:choice with the dialog's outcome: accepted or dismissed.

Only Chromium browsers (Chrome, Edge, Samsung Internet) let a page open the install dialog. In Safari, users install with Share > Add to Home Screen, and the button stays hidden.

Track the PWA From JavaScript#

The pwa_head() script dispatches these events on document:

Event When detail
phem:installable The browser can install the app prompt: the beforeinstallprompt event
phem:installed The user installed the app
phem:pwa-updated A new service worker version controls the page

It also keeps the last beforeinstallprompt event in window.phemInstallPrompt.

A new service worker version takes control right away. You get one when you change the phem.pwa options or update Phem. Ask the user to reload:

document.addEventListener('phem:pwa-updated', () => {
    if (confirm('A new version is available. Reload?')) location.reload()
})

PWA Options Reference#

Option Default What it does
pwa.enabled false Turns on the PWA
pwa.name null The app's name. Required
pwa.short_name null The name under the icon, when name is too long
pwa.description null What the app does
pwa.lang null The language of the name and description
pwa.start_url / The URL the installed app opens first
pwa.scope / The app's URLs, and the service worker's scope
pwa.display standalone fullscreen, standalone, minimal-ui or browser
pwa.theme_color null The title bar color. pwa_head() renders it as <meta name="theme-color">
pwa.background_color null The splash screen color
pwa.icons [] The icons: src, sizes (any), type (from the extension) and purpose
pwa.offline_page null The path of the page to show when the network fails
pwa.manifest_path /manifest.webmanifest The manifest's path
pwa.service_worker_path /sw.js The service worker's path
pwa.cache.pages false Keeps a copy of each page (network first), except pages that used the session
pwa.cache.max_pages 50 The maximum number of cached pages
pwa.cache.assets true Keeps the files under assets_prefix (cache first)
pwa.cache.assets_prefix /assets/ The path of the versioned assets
pwa.cache.precache [] Extra paths to cache when the worker installs

All paths must start with /.

Edit this page on GitHubLast updated
Phem
Esc
↑↓ to navigate↵ to openEsc to close