Search by

peter9x / laravel-pwa

eletronik

Friendly PWA tooling for Laravel: dynamic manifest, a configurable service worker, several PWAs per application, icon generation and ready-to-use React hooks and components (Inertia optional).

Package info

github.com/peter9x/laravel-pwa

pkg:composer/peter9x/laravel-pwa

Statistics

Installs: 10

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.2.0 2026-11-30 22:37 UTC

This package is auto-updated.

Last update: 2026-11-30 22:38:29 UTC


README

tests

Turn a Laravel application into an installable, offline-aware Progressive Web App, following current PWA best practices - without Workbox, extra npm dependencies or build steps. Built for Inertia + React, and just as usable by a single-page app or plain Blade.

  • Dynamic manifest served from config/pwa.php (nothing to regenerate).
  • Service worker served by Laravel, versioned automatically on every deploy. Navigation and caching strategies are configuration, not code.
  • Several PWAs per application, each on its own domain or prefix.
  • React hooks and components (TypeScript) imported straight from the package, so they stay in sync with it: install prompt (with iOS instructions), update prompt and offline indicator.
  • Icon generator: icons, maskable icons, Apple touch icon and iOS splash screens from a single image.
  • pwa:doctor to check installability requirements and your configuration.
  • CSP friendly: no inline scripts.

Upgrading from 0.1? See UPGRADE.md.

Requirements

  • PHP 8.2+ and Laravel 12 or 13
  • Vite. The components need React 18 or 19 and Tailwind; registerPwa() and the service worker need neither. Inertia 2 is optional.
  • The GD extension, only for pwa:icons
  • HTTPS in production (service workers also work on localhost)

Installation

composer require peter9x/laravel-pwa
php artisan pwa:install

pwa:install:

  1. publishes config/pwa.php;
  2. copies a default icon set to public/pwa;
  3. makes @laravel-pwa point to the helpers of the package: an alias in vite.config.js, paths in tsconfig.json and a Tailwind @source in resources/css/app.css;
  4. adds @pwaHead to resources/views/app.blade.php;
  5. imports and calls registerPwa() in resources/js/app.tsx - plus registerInertiaOffline() when the project uses @inertiajs/react.

Whatever it cannot patch is listed at the end, to do by hand. Use --no-patch to skip steps 3 to 5, and --force to overwrite files that already exist.

Then render the components once, for the whole app:

import { InstallPrompt, OfflineIndicator, UpdatePrompt } from '@laravel-pwa';

createRoot(el).render(
    <>
        <App {...props} />
        <InstallPrompt />
        <UpdatePrompt />
        <OfflineIndicator />
    </>,
);

Finally, generate your own icons and check the setup:

php artisan pwa:icons resources/images/icon.png
php artisan pwa:doctor

The service worker is only registered in production builds (npm run build). Pass registerPwa({ enabledInDev: true }) to try it with the Vite dev server.

The @laravel-pwa alias

The helpers live in vendor/peter9x/laravel-pwa/resources/js and are imported from there, so a composer update updates them together with the service worker. What pwa:install writes:

// vite.config.js
resolve: {
    alias: {
        '@laravel-pwa': '/vendor/peter9x/laravel-pwa/resources/js',
    },
},
// tsconfig.json
"paths": {
    "@laravel-pwa": ["./vendor/peter9x/laravel-pwa/resources/js/index.ts"],
    "@laravel-pwa/*": ["./vendor/peter9x/laravel-pwa/resources/js/*"]
}
/* resources/css/app.css (Tailwind 4 does not scan vendor/) */
@import 'tailwindcss';
@source '../../vendor/peter9x/laravel-pwa/resources/js';

Prefer to own the code? php artisan pwa:install --publish copies it to resources/js/pwa (install.js_path) and imports it with a relative path instead. pwa:doctor then warns when your copy falls behind the package.

Custom paths

When your app does not use the default layout (for example, a separate admin app with its own root view and entry point), point the commands at your files with install in config/pwa.php:

'install' => [
    'root_view' => 'resources/views/admin/app.blade.php',
    'entry' => 'resources/js/admin/app.tsx',
    'js_path' => 'resources/js/admin/pwa',
],

or with the --view, --entry and --js-path options, which take precedence. pwa:doctor accepts the same options and reads the same config.

Recipes

Inertia with an offline page

The default configuration. Navigations always go to the network; without a connection the visitor gets the offline page, and an Inertia visit that fails keeps the current page on screen while <OfflineIndicator /> explains why.

'service_worker' => [
    'navigation' => [
        'strategy' => 'network-first',
        'fallback' => 'offline-page',
    ],
],
import { registerPwa } from '@laravel-pwa';
import { registerInertiaOffline } from '@laravel-pwa/inertia';

registerPwa();
registerInertiaOffline();

HTML pages are not cached on purpose: Inertia pages embed user data.

Single-page app with an app shell

For an app whose routes are all rendered by the same HTML document (React Router, TanStack Router...). The shell is cached when the worker installs, answers every navigation without waiting for the network, and is refreshed in the background whenever there is a connection - so the app opens offline.

'service_worker' => [
    'navigation' => [
        'strategy' => 'app-shell',
        'fallback' => 'app-shell',
        'app_shell' => '/',            // null: the manifest start_url
        'allow' => ['/*'],             // navigations this applies to
    ],
    'runtime' => [
        ['match' => '/build/*', 'strategy' => 'cache-first'],
        ['match' => ['image', 'font'], 'strategy' => 'stale-while-revalidate', 'max_entries' => 80],
        ['match' => '/api/catalog/*', 'strategy' => 'network-first'],
    ],
],
import { registerPwa } from '@laravel-pwa/register'; // no React, no Inertia

registerPwa();

The app shell must answer 200 without redirecting, for everyone: it is the same document for every visitor, so keep user data out of it (load it from your API) and do not put it behind a redirect to a login page. pwa:doctor checks this. With 'strategy' => 'network-first' and 'fallback' => 'app-shell' the shell is only used when the network fails.

A PWA on a subdomain

domain binds the manifest, service worker and offline routes to one host; they answer 404 everywhere else.

'domain' => env('PWA_DOMAIN'), // app.example.com

Several PWAs in one application

Declare them in apps. Each one has its own domain or prefix, manifest, service worker, caches and assets, and inherits whatever it does not set from the top level of the file.

'manifest' => ['theme_color' => '#4f46e5'],   // shared by every app

'default' => 'backoffice',

'apps' => [
    'backoffice' => [
        'manifest' => ['name' => 'Backoffice'],
    ],
    'checkin' => [
        'domain' => env('CHECKIN_APP_DOMAIN'),
        'manifest' => ['name' => 'Check-in', 'short_name' => 'Check-in'],
        'assets' => ['path' => 'pwa/checkin', 'icon' => 'resources/images/checkin.png'],
        'service_worker' => [
            'navigation' => ['strategy' => 'app-shell', 'fallback' => 'app-shell'],
            'precache' => ['vite_entries' => ['resources/js/checkin_app/main.tsx']],
        ],
        'install' => [
            'root_view' => 'resources/views/checkin.blade.php',
            'entry' => 'resources/js/checkin_app/main.tsx',
        ],
    ],
    'kiosk' => [
        'prefix' => '/kiosk',                 // /kiosk/sw.js, scope and start_url "/kiosk"
        'manifest' => ['name' => 'Kiosk'],
    ],
],
@pwaHead('checkin')   {{-- @pwaHead alone renders the default app --}}
php artisan pwa:install --app=checkin
php artisan pwa:icons --app=checkin
php artisan pwa:doctor --app=checkin   # without --app: every app

Routes are named pwa.{app}.manifest, pwa.{app}.sw and pwa.{app}.offline (pwa.manifest, pwa.sw and pwa.offline without apps). A page that renders a single @pwaHead needs nothing else; registerPwa({ app: 'checkin' }) picks the tags of one app when a page renders several.

Icons, splash screens and background image

Everything lives in a single folder, public/pwa (configurable with assets.path).

php artisan pwa:icons resources/images/icon.png \
    --background="#0f172a" \
    --background-image=resources/images/splash-background.jpg
File Purpose
icon-192.png, icon-512.png Manifest icons (purpose: any)
icon-maskable-192.png, icon-maskable-512.png Maskable icons, padded to the safe zone on the background colour
apple-touch-icon.png iOS home screen icon (180x180, opaque)
favicon-32.png Optional favicon
splash-*.png iOS / iPadOS launch screens, linked automatically by @pwaHead

Options:

  • source - at least 512x512 (1024x1024 recommended). Defaults to assets.icon.
  • --app - the PWA to generate them for (default: the default app).
  • --background - defaults to manifest.background_color.
  • --background-image - fills the splash screens (cropped to cover), with the icon centred on top. Defaults to assets.background_image.
  • --padding - padding of maskable icons (default 0.1). Use 0 when your source image already includes its own safe area.
  • --no-splash - skip the splash screens.

assets.background_image (a path inside public/, e.g. pwa/background.jpg) is also used as the background of the offline page.

To use icons that live somewhere else, declare them in manifest.icons.

Configuration

config/pwa.php is documented inline. Every option except enabled, debug, default and apps can also be set per app.

Option Description
enabled PWA_ENABLED. When false, a kill-switch worker unregisters the PWA from browsers that installed it.
domain, prefix Host the routes are bound to, and sub-path the PWA is served from.
manifest.* Any web app manifest member: name, colours, display, shortcuts, screenshots... id, start_url and scope default to the prefix (or /).
manifest.theme_color_dark Optional theme colour for dark mode.
service_worker.skip_waiting prompt (default): a new version waits until the user accepts it. auto: it activates right away and reloads the open pages.
service_worker.precache.vite Precache every file of the Vite build (default true).
service_worker.precache.vite_entries Only precache what these Vite entries reach (patterns, * wildcard), e.g. an admin app sharing the build with a public site. Empty: the whole build.
service_worker.precache.urls Extra URLs to precache.
service_worker.navigation.* How page navigations are answered: see below.
service_worker.runtime Caching rules for every other request: see below.
service_worker.exclude Shorthand for network-only rules: paths the worker never handles (/api/*, /horizon*...). Requests made by an excluded page go straight to the network too.
install_prompt.enabled PWA_INSTALL_PROMPT. Show <InstallPrompt /> when the app is opened in the browser (default true).
install_prompt.delay Seconds to wait before showing the prompt (default 0).
install_prompt.remind_after_days Days the prompt stays hidden after being dismissed (default 14); 0 shows it again the next time the app is opened.
routes.* URLs of the manifest and of the offline page, relative to the prefix.
offline.* Texts of the offline page.

The package defaults are merged recursively under your published file: options added by a new version get their default value without republishing it. pwa:doctor lists the options your file is missing and the ones the package does not know (typos).

To customise the offline page markup:

php artisan vendor:publish --tag=pwa-views

Navigation

navigation.strategy A navigation is answered with
network-first (default) the network; the fallback when it fails
app-shell the cached app_shell, at once; it is refreshed in the background
cache-first the cached copy of that page when there is one (up to max_entries pages), the network otherwise
navigation.fallback A navigation that fails gets
offline-page (default) the page at routes.offline
app-shell the cached app_shell
none the browser error page

navigation.allow lists the paths this applies to (* wildcard); other navigations are left to the browser. The offline route only exists when the fallback is offline-page.

Runtime caching rules

'runtime' => [
    ['match' => '/build/*', 'strategy' => 'cache-first'],
    ['match' => ['image', 'font'], 'strategy' => 'stale-while-revalidate', 'max_entries' => 80],
    ['match' => '/reports/*', 'strategy' => 'network-first', 'cache' => 'reports'],
    ['match' => 'video', 'strategy' => 'network-only'],
],

match is a path pattern (* wildcard), a request destination (image, font, style, script...) or a list of both. The first rule that matches wins; exclude is checked before them. Strategies: cache-first, stale-while-revalidate, network-first and network-only. Each rule has its own cache, bounded by max_entries. Requests that match no rule are left to the browser, and the Vite build is always cached, even without a rule for it.

Frontend API

import { usePwaInstall, usePwaUpdate, useOnlineStatus } from '@laravel-pwa';

function InstallButton() {
    const { canInstall, needsManualInstall, isInstalled, install } = usePwaInstall();

    if (canInstall) {
        return <button onClick={() => install()}>Install</button>;
    }

    // iOS has no install prompt: explain "Share → Add to Home Screen".
    return needsManualInstall ? <IosInstructions /> : null;
}
Export Description
registerPwa(options?) Starts everything. Options: app, enabledInDev, updateInterval. Also at @laravel-pwa/register, free of React.
registerInertiaOffline() From @laravel-pwa/inertia: keeps the current page when an Inertia visit fails offline.
promptInstall(), applyUpdate(), checkForUpdate() What the hooks call, for code outside React.
usePwaInstall() canInstall, isInstalled, isIos, needsManualInstall, install().
usePwaUpdate() updateAvailable, update(), checkForUpdate().
useOnlineStatus() isOnline, isOffline, lastFailedVisit.
<InstallPrompt /> Install dialog shown on page open; remembers when it was dismissed.
<UpdatePrompt /> "A new version is available" banner.
<OfflineIndicator /> Banner shown while offline.

Components are styled with Tailwind classes and take their texts and classes as props, so they are translated and themed without copying them:

<InstallPrompt
    title="Instalar a app"
    description="Fica no ecrã principal, em ecrã inteiro e disponível sem rede."
    installLabel="Instalar"
    dismissLabel="Agora não"
    iosSteps={['Toque em Partilhar na barra do browser.', 'Escolha "Adicionar ao ecrã principal".']}
    installClassName="bg-brand text-brand-dark"
/>

Install prompt on page open

By default <InstallPrompt /> invites visitors to install the app as soon as they open it in the browser. Turn that off in config/pwa.php (or with PWA_INSTALL_PROMPT=false) and offer installation from your own UI instead, with usePwaInstall():

'install_prompt' => [
    'enabled' => env('PWA_INSTALL_PROMPT', true),
    'delay' => 0,              // seconds before it shows
    'remind_after_days' => 14, // after "Not now"
],

The enabled, delay, remindAfterDays and icon props override the configuration for a single <InstallPrompt />.

The hooks are safe to use with Inertia SSR.

How the service worker behaves

Request Default strategy
Page navigations Network first; the offline page when there is no connection
Inertia visits (X-Inertia) Network only, never cached
Vite build assets (/build/*) Precached on install, cache first
Images and fonts Stale-while-revalidate, bounded
POST/PUT/..., other origins, excluded paths Not handled
  • Versioning - the cache version is a hash of the Vite manifest, the PWA configuration and the worker itself. Deploying a new build is all it takes for browsers to pick up the update.
  • Updates - a new worker waits until the user accepts the update in <UpdatePrompt /> (or update()), then the page reloads. Users are never switched to new assets in the middle of a session, unless you opt in with skip_waiting: auto.
  • Protocol - the page and the worker exchange versioned messages ({ type, protocol }). The worker ignores protocols it does not know and still understands the 0.1 helpers.

Blade and PHP

<head>
    ...
    @pwaHead
</head>
use Peter9x\LaravelPwa\Facades\Pwa;

Pwa::manifest();            // the manifest of the default app, as an array
Pwa::manifest('checkin');   // ...of another app
Pwa::version();             // current service worker / cache version
Pwa::head();                // what @pwaHead renders
Pwa::apps();                // every app, keyed by name
Pwa::app('checkin')->serviceWorkerUrl();

Deployment notes

  • Run npm run build before serving: the precache list comes from public/build/manifest.json.
  • /sw.js, /manifest.webmanifest and /offline are Laravel routes. If your web server answers *.js requests itself (some nginx configs do), let these reach Laravel, e.g. location = /sw.js { try_files $uri /index.php?$query_string; }.
  • The routes are public and cookie-less by design; do not put them behind auth.
  • Run php artisan pwa:doctor after changing the configuration: it requests the manifest, the service worker and the app shell on the domain of each app.

Testing

composer test   # Pest
composer lint   # Pint
npm run types   # type-check the frontend helpers
npm test        # the service worker, with Vitest

License

MIT - see LICENSE.