Today we are going to learn how we can create a Progressive Web App (PWA) using React and Next.js.
We install the dependency we are going to use next-pwa
npm install next-pwa --save-dev @types/next-pwa --save-dev
Now we create a manifest.json file inside public.
{ "short_name": "My PWA", "name": "My PWA", "icons": [ { "src": "/icon.png", "sizes": "192x192", "type": "image/png" } ], "start_url": "/", "display": "standalone", "theme_color": "#ffffff", "background_color": "#ffffff" }
We put the name and data of our app and link the icon. We can choose the orientation by indicating: «orientation»: «portrait»
We create a file named service-worker.js inside public:
self.addEventListener('install', function(event) { event.waitUntil( caches.open('cache01').then(function(cache) { return cache.addAll([ '/_next/static/', // Here you should add the routes to the static files generated by Next.js ]); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response fetch(event.request); }) ); }); var cacheWhitelist = ['cache01']; caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (cacheWhitelist.indexOf(cacheName) === -1) { return caches.delete(cacheName); } }) ); }); caches.keys().then(function(cacheKeys) { console.log('SW Version: '+cacheKeys); });
We add the manifest.json to our head:
<link rel="manifest" href="./manifest.json" />
And now we load the web in the Chrome mobile browser to see how it prompts us to install the APP or we go to Settings and click on Install application.