React + PWA (Progressive Web App)
PWA stands for progressive web app. This is an app built from the web technologies like HTML, CSS, and JavaScript (Library / Framework) but with a feel and functionality that rivals an actual native app. You can offer all the features of native apps, like push notifications, offline support, and much more. Dozens of major brands have reinforced their mobile efforts and released PWAs, like Flipkart, Twitter, Pinterest, Starbucks, etc. PWA offers following benefits for your websites.
- Native like experience :
It provides a mobile-like experience. It is a web app but it feels like you are interacting with an Android/iOS app.
- Responsiveness :
It can match to fit any screen size be it a tablet, mobile, iPad or desktop. It automatically adjusts to compensate for either a new space or a narrow space.
- Offline support :
You can run your website/App offline in offline mode.
- Push Notification :
PWAs are engaging with the use of push notifications, they pop up a notification to notify about either a friend request, current news, new message or any other thing, you will feel the urge to respond to the notification (to respond to the message, to read the news, to check out the new friend) and launch the app again, thereby re-engaging you with the web app.
- Progressive enhancement:
It works for every user no matter the browser choice of the user. Your app will run properly on a wide range of browsers and will degrade gracefully when certain functionalities are not available but still with a decent user experience.
Currently browsers like Google Chrome for Android, Mozilla Firefox for Android, Edge for Android, Brave for Android and Samsung Internet are the browsers that support PWA now.
Note: IE (Internet Explorer) browser does not support PWA.
Covert React application to PWA (Progressive web app):
Now we will see how to convert any react application to PWA (Progressive web app), by the end of the step we can able to install our app as android application and as a windows application and we will also be used our application in offline mode. For creating react app use following command and create your own application on local.
Command: npx create-react-app nameofapp
I was already developed a react application on my local environment, below is the interface of my application when it render with active internet connection.
But when you turn off the internet connection or go to network tab and select offline it will not render the application instead of we get page like below.
We need to load this page even if the there are no internet connection, for that we need to add the service worker application.
Service Worker:
Service Workers is a type of Worker that lets us run scripts in the background of our browser. It is like a man-in-the-middle between our browser and the network. The main work of Service workers is to help us cache and serve the cached files which provide an uninterrupted user experience.
- Register a service worker:
For adding service worker in our application we need to first check for browser is compatible with service worker or not. For this we need to add following lines in our index.html file.
<script>
if('serviceWorker' in navigator) {
window.addEventListener('load', ()=> {
navigator.serviceWorker.register('./serviceWorker.js')
.then((reg) => console.log('Success', reg.scope))
.catch((err) => console.log('Failure', err))
})
}
</script>
The condition above is find out service worker is compatible with browser or not, if it compatible then we will add an event listener on load of page and register our service worker when the page is first load.
Tip: If you don’t want to add above lines in index.html file. You can create a java script file and add register () function in there and add above code there, call this function in index.js file. Just make sure you can redirect to correct path of a serviceWorker.js file.
- Install service worker:
After that we need to create a serviceWorker.js file in our public folder. We need to add the cache name in our service worker file in which we can add our offline pages. Add an event listener on install of service worker, on success callback of event listener we add the promise inside event.waitUtil( ), on success of cache opened we can add the pages along with route of the pages you want to store in cache storage on your browser.
In my case I want to store the three react bundles with index.html file and ‘/’ is the route along with that I also stored the background image in cache. The reason for this is I want my application to behave exactly as it working with active internet connection when internet connection deactivate.
const CACHE_NAME = 'Vesion-1';
self = this;
// Install ServiceWoker
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => {
console.log('Added cache name');
return cache.addAll([
'/static/js/bundle.js',
'/static/js/0.chunk.js',
'/static/js/main.chunk.js',
'index.html',
'/images/background.jpg',
'/',
]);
})
)
});
- Fetch request:
Now we have to fetch the request, for that we will add the event listener on fetch, on success callback we will first check the internet connection is offline or not, if it is then add event.respondWith( ), inside that we will add promise that match the caches with each requests and on success of promise we will simply fetch the request by cloning the request.
// fetch request
self.addEventListener('fetch', (event) => {
if (!navigator.onLine) {
event.respondWith(
caches.match(event.request)
.then((result) => {
if (result) { return result; }
const requestUrl = event.request.clone();
return fetch(requestUrl)
}
)
)
}
});
Tip: If don’t want cache all the pages or if your application is too large then you can just simply show the offline page when the internet is not active just like twitter. For that create an offline.html page and add this to cache add following code to service worker.
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then(() => {
return fetch(event.request)
.catch(() => caches.match('offline.html'))
})
)
});
- Activate the service worker:
Now we have to activate the service worker, for this add an event listener on activate, In this particular success callback we have to delete the existing caches and add only caches that we need to run our application. For that add promise cache.keys( ) it will return array of existing caches in that particular array delete all the other cache and store only cache that we added for our application on installation of service worker.
//Activate serviceWorker
self.addEventListener('activate', (event) => {
const cacheWhiteList = [];
cacheWhiteList.push(CACHE_NAME);
event.waitUntil(
caches.keys().then((cacheNames) => {
cacheNames.map((cacheName) => {
if (!cacheWhiteList.includes(cacheName)) {
return caches.delete(cacheName);
}
})
})
)
});
This is all about the serviceWorker.js file, now you can run the project and it’s now working when internet is turned off. But you still not able to install your application as windows or android app. For that we need to add the manifest.json in our project public folder.
Manifest :
{
"short_name": "Covid19 Tracker App",
"name": "Covid19 Tracker App PWA",
"icons": [
{
"src": "/images/logo.png",
"type": "image/png",
"sizes": "900x900",
"purpose": "any maskable"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
Above is the sample manifest.json file, add the name, short name of you app and the most importantly add the icons that want to display logo of your application.
Tip: You can also store you API response in local storage and used it when the app is offline, also show the warning that user is offline.
Now you create a build and run the project for that run following command.
Command: npm run build && npm install –g serve && serve - s build
OR
Command: npm run start
Now load you application it will load as it is but this time when you go to offline mode in your network tab it will not showing the offline page instead of it is showing the pages that you are stored in cache.
Now go to chrome lighthouse tool and generate report now and see the result.
We covered all the check points except one i.e. does not reflect HTTP traffic to HTTPS. To resolve this we need to deploy our application to AWS or for testing purpose use Netlify. By default it will run on localhost and it is not secure. When you deploy your application to on AWS and then check the lighthouse report you can see we achieve all the check points of lighthouse report. Now we can see we are able to add our project as windows application and if you open this in android studio it will give option to add to home screen.
Summary:
In this article, we learned about how we can make PWA install able with a properly-configured web manifest, and how the user can then install the PWA with the "add to home screen" feature of their browser.
Very useful