Certainly! Making a Laravel + InertiaJS + VueJS app work offline as a PWA requires careful handling of caching, especially for Inertia responses, which are JSON payloads.
Key Points:
- Inertia responses are JSON, not HTML.
- Service Workers must cache both static assets and XHR/fetch API responses.
- You need to intercept and cache Inertia requests (usually to
/apior/endpoints returning JSON).
Solution Steps:
-
Install Laravel PWA Package (optional): You can use packages like
cretueusebiu/laravel-web-pushorsilviolleite/laravel-pwafor manifest and service worker scaffolding, or roll your own. -
Create/Modify Service Worker: Your service worker must cache:
- Static assets (JS, CSS, images)
- Inertia JSON responses
Here’s a basic example of a service worker (
public/service-worker.js):const CACHE_NAME = 'my-pwa-cache-v1'; const STATIC_ASSETS = [ '/', '/js/app.js', '/css/app.css', // add other static assets here ]; self.addEventListener('install', event => { event.waitUntil( caches.open(CACHE_NAME) .then(cache => cache.addAll(STATIC_ASSETS)) ); }); self.addEventListener('fetch', event => { // Handle Inertia JSON requests if ( event.request.headers.get('X-Inertia') === 'true' && event.request.method === 'GET' ) { event.respondWith( caches.match(event.request) .then(response => { return response || fetch(event.request).then(fetchResponse => { return caches.open(CACHE_NAME).then(cache => { cache.put(event.request, fetchResponse.clone()); return fetchResponse; }); }); }) .catch(() => { // Optionally, return a fallback JSON response return new Response(JSON.stringify({offline: true}), { headers: {'Content-Type': 'application/json'} }); }) ); return; } // Default: cache-first for static assets event.respondWith( caches.match(event.request).then(response => { return response || fetch(event.request); }) ); }); -
Register the Service Worker in your Vue app:
In your main JS file (e.g.,
app.js):if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/service-worker.js'); }); } -
Test Offline:
- Open DevTools > Application > Service Workers.
- Check "Offline" and reload.
- Your Inertia pages should load from cache.
Tips:
- Make sure your Inertia requests include the
X-Inertia: trueheader (Inertia does this by default). - For more advanced caching (stale-while-revalidate, cache expiration), consider using Workbox.
References:
Let me know if you need a more advanced example or help with Workbox!