Laravel PWA using WorkBox – Tips

Building a PWA (Progressive web app) has been made super simple using Google workbox package. Workbox can generate a complete javascript service worker for you. 

“Workbox is a set of libraries and Node modules that make it easy to cache assets and take full advantage of features used to build Progressive Web Apps.”

IN your existing Laravel project :

Step 1:
Install workbox : we will install it globally

npm install workbox-cli –global

Step 2: In your layout view (app.blade.php) Add the following: This will load the service worker file which workbox will generate for you.

service worker is a type of web worker. It’s essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages

<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
  // Use the window load event to keep the page load performant
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js');
  });
}
</script>

You can wrap the above script tag in :

@if (App::environment(‘production’, ‘staging’))

so files are not cached while in development environment and a service worker requires https to load correctly:

Step 3:

Add a link to your manifest file in your layout :

The web app manifest provides information about an application (such as its name, author, icon, and description) in a JSON text file

<link rel=”manifest” href=”/manifest.json”>

example manifest file :

{
"name": "My App",
"short_name": "My App",
"start_url": "/",
"display": "standalone",
"gcm_sender_id": "0000",
"background_color": "#FFFFF8",
"theme_color": "#8CB84E",
"icons": [{
"src": "ico/favicon-128.png",
"type": "image/png",
"sizes": "128x128"
}, {
"src": "ico/icon-512x512.png",
"type": "image/png",
"sizes": "512x512"
}, {
"src": "ico/apple-touch-icon-152x152.png",
"type": "image/png",
"sizes": "152x152"
}, {
"src": "ico/mstile-144x144.png",
"type": "image/png",
"sizes": "144x144"
}, {
"src": "ico/chrome-touch-icon-192x192.png",
"type": "image/png",
"sizes": "192x192"
}]
}

Step 4

In the root of your project, create a file called workbox-config.js
Here is an example file. please read the docs https://developers.google.com/web/tools/workbox/
This is the configuration file, Workbox will use to generate your service worker.

module.exports = {
cacheId: 'hr-app-'+Math.floor(Date.now() / 1000),
globDirectory: "public/",
globPatterns: [
"**/*.{css,ico,eot,svg,ttf,woff,woff2,js,json}",
"images/*.{png,jpg,jpeg,gif,bmp}",
],

swDest: "public\\sw.js",
// Define runtime caching rules.
runtimeCaching: [
{
urlPattern: "/",
handler: 'networkFirst',

},

],
};

Whats important here you will notice that I have used a variable name for the cache id . Why I did this was , to break the cache when pushing changes into production.
Simply having Laravel mix handle cache busting by having  .version in my mix-manifest did not work. (The cache busting query string not included when files cached)
They might be a better solution to this , if you do know, please leave a comment below.

Step 5

In order to generate the sw.js file which the browser will load , you need to call Workbox CLI, to automate this , you can add the following in your package.json file under  scripts -> production section. So when you run “npm run prod” your service worker file is generated.

"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js && workbox generateSW workbox-config.js"


Step 6

Add this to your .htaccess so that your service worker file itself is not cached

<Files sw.js>
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</Files>

And thats the gist of it. You will need to spend time on step 4 and tune your Workbox configuration file to your site requirements.
Don’t forget you can view your application cache and site manifest in Chrome developer tools in your browser under the applications tab…