Build a Progressive Web App using React

Published on Feb 1, 2018

12 min read

REACTJS

Originally this article was published on Zeolearn.com

cover_image

Progressive Web App with React! When I read this I thought, why not build one ourselves. If you are familiar with React and a bit about its ecosystem such as Create-React-App utility, this guide is for you.

If you spend at least third quarter of your day on internet then you have seen or read about progressive web apps here and there. No? PWA are performance focused web applications that are especially streamlined for a mobile device. They can be saved over a device’s home screen and tend to consist a native app feel and look. The first PWA app I used on my mobile device is the Lite Twitter one which got released a few months back. Here is the link if you want to try: https://lite.twitter.com/. They even support push notifications and offline support these days.

Getting Started

🔗

Let us create a basic React app using Create-React-App generator, the official scaffolding tool to generate Reactjs App released and maintained by Facebook. To install it, we will use our command line tool:

npm install --global create-react-app

Once the installation process is complete, go to your desired directory and create an empty project. Run this from your command-line interface:

create-react-app react-pwa-example
# and cd in that directory
cd react-pwa-example

Go ahead and take a look at the directory structure and package.json file. See what dependencies come with this scaffolding tool.

CRA or Create React App is one of the best with minimum hassle tool that I am currently using to build apps and prototypes with React. It is running all that Babel, Webpack stuff behind the scenes. If you want more information or want to customize the process, read here.

I hope, regardless of the timeline, your package.json file looks like this:

1{
2 "name": "react-pwa-app",
3 "version": "0.1.0",
4 "private": true,
5 "dependencies": {
6 "react": "^16.2.0",
7 "react-dom": "^16.2.0",
8 "react-scripts": "1.0.17"
9 },
10 "scripts": {
11 "start": "react-scripts start",
12 "build": "react-scripts build",
13 "test": "react-scripts test --env=jsdom",
14 "eject": "react-scripts eject"
15 }
16}

We need to one more dependency and that is React-Router: Go Back to your terminal:

npm install --save react-router-dom@4.2.2

You can now try running the application from terminal and see if everything is working:

npm run start

The boilerplate code will and look like this:

Building the PWA App

🔗

Since the sole purpose of this guide is to make you familiar with the build process, I am not going to work out a complex application. For sake of simplicity and your precious time, we will build a simple app. Go to src/App.js file and make amendments exactly like below:

1import React, { Component } from 'react';
2import { BrowserRouter, Route, Link } from 'react-router-dom';
3import logo from './logo.svg';
4import './App.css';
5import Home from './components/Home';
6import About from './components/About';
7
8class App extends Component {
9 render() {
10 return (
11 <div className="App">
12 <div className="App-header">
13 <img src={logo} className="App-logo" alt="logo" />
14 <h2>React App</h2>
15 </div>
16 <BrowserRouter>
17 <div>
18 <Route path="/" exact component={Home} />
19 <Route path="/about" exact component={About} />
20 </div>
21 </BrowserRouter>
22 </div>
23 );
24 }
25}
26export default App;

In above we are including two pages using react-router-dom.Further we define Home and About Components in src/components/ directory. It is always a best practice to use this approach and make sure that react components are short and readable.

For Home.js:

1import React from 'react';
2import { Link } from 'react-router-dom';
3
4const home = () => {
5 return (
6 <div title="Home">
7 <h1>Home Page</h1>
8 <p>
9 <Link to="/about">About</Link>
10 </p>
11 </div>
12 );
13};
14
15export default home;

And for About.js:

1import React from 'react';
2import { Link } from 'react-router-dom';
3
4const about = () => {
5 return (
6 <div title="About">
7 <h1>About Page</h1>
8 <p>
9 <Link to="/">Home</Link>
10 </p>
11 </div>
12 );
13};
14
15export default about;

Now to see if everything working, run npm start from your terminal window, and you will get a similar result:

If you click on the About button/hyperlink, the react-router-dom will render the about page without changing the common Header part that is defined in App.js. This is a bare minimum single page application.

Our main job is still yet to be done. Let’s convert this bare minimum React application to a PWA.

Installing Lighthouse

🔗

Lighthouse is a free tool from Google that evaluates your app based on their PWA checklist. Add it to your Chrome browser from here. Once installed as an extension we can start the auditiing process by clicking on the Lighthouse at top right corner where other extension might exist in your browser. Click on the icon and then make sure you are on right tab by checking the URL shown in the lighthouse popup. Also, make sure that development server of Create-react-app from terminal is running. Otherwise Lighthouse won’t be able to generate report. The report that is generated by the Lighthouse is based on a checklist that available to view here.

Click on the Generate Report button. After the process is completed, a new window will open where Lighthouse has generated a report. By the looks of it, it does not look pleasing to the Lighthouse and as a Progressive Web App.

We will be solving these issues one by one.

Setting up a Service Worker

🔗

Let’s setup a service worker first. That is the first thing Lighthouse audited. What is a service worker, you ask? Well, it is a proxy server that sit between web applications, browsers and the network. We can use it to make React Apps work offline (remember the earlier point we discussed. Progressive Web Apps are focused on performance). You can definitey read details about it on Google’s Web Fundamental Docs.

It is a two step process. First we will create aservice-worker.js file (service worker, after all is JavaScript code) and then register that worker in our index.html.

In the public directory of our app strucutre, create a file service-worker.js. I am going to use Addy Osmani's service worker configuraiton and I will recommend you to do so, at least for this one. You can find the complete thing in much much detail here. To continue, make sure you add the following code in service-worker.js file:

1var doCache = false;
2
3var CACHE_NAME = 'my-pwa-cache-v1';
4
5self.addEventListener('activate', event => {
6 const cacheWhitelist = [CACHE_NAME];
7 event.waitUntil(
8 caches.keys().then(keyList =>
9 Promise.all(
10 keyList.map(key => {
11 if (!cacheWhitelist.includes(key)) {
12 console.log('Deleting cache: ' + key);
13 return caches.delete(key);
14 }
15 })
16 )
17 )
18 );
19});
20
21self.addEventListener('install', function (event) {
22 if (doCache) {
23 event.waitUntil(
24 caches.open(CACHE_NAME).then(function (cache) {
25 fetch('manifest.json')
26 .then(response => {
27 response.json();
28 })
29 .then(assets => {
30 const urlsToCache = ['/', assets['main.js']];
31 cache.addAll(urlsToCache);
32 console.log('cached');
33 });
34 })
35 );
36 }
37});
38
39self.addEventListener('fetch', function (event) {
40 if (doCache) {
41 event.respondWith(
42 caches.match(event.request).then(function (response) {
43 return response || fetch(event.request);
44 })
45 );
46 }
47});

Our next step is to register the our service worker by loading the one we just wrote in service-worker.js. Add this before the closing </body> tag in index.html.

1<script>
2 if ('serviceWorker' in navigator) {
3 window.addEventListener('load', function () {
4 navigator.serviceWorker
5 .register('service-worker.js')
6 .then(
7 function (registration) {
8 console.log(
9 'ServiceWorker registration successful with scope: ',
10 registration.scope
11 );
12 },
13 function (err) {
14 console.log('ServiceWorker registration failed: ', err);
15 }
16 )
17 .catch(function (err) {
18 console.log(err);
19 });
20 });
21 } else {
22 console.log('service worker is not supported');
23 }
24</script>

Make sure you restart the dev server by running npm run start from the terminal. You must see this line if you open Chrome's DevTools > Console:

If we run the Lighthouse audit process again, I hope we will get a better result.

Yes, you can clearly compare the above with our previous audit. It has imporved, and our previous first issue is now coming under Passed Audits. Now let’s move and add some enhancement.

Adding Progressive Enhancement

🔗

Progressive Enhancement is way to improve the app/site since it will work without any JavaScript loading. Now, we want to display a loading message and some CSS or none (your choice) before the React app initializes the DOM. Let’s add a the required CSS and a loading message to our index.html. To increase performance, I am also adding all our CSS (that is CSS contained inside App.css and index.css) in our index.html file.

1<!DOCTYPE html>
2<html lang="en">
3
4<head>
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
7 <meta name="theme-color" content="#000000">
8 <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
9 <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
10 <title>React App</title>
11 <style type="text/css">
12 body {
13 margin: 0;
14 padding: 0;
15 font-family: sans-serif;
16 }
17 .App {
18 text-align: center;
19 }
20 .App-logo {
21 height: 80px;
22 }
23 .App-header {
24 background-color: #222;
25 height: 150px;
26 padding: 20px;
27 color: white;
28 }
29 .App-title {
30 font-size: 1.5em;
31 }
32 .App-intro {
33 font-size: large;
34 }
35 @keyframes App-logo-spin {
36 from {
37 transform: rotate(0deg);
38 }
39 to {
40 transform: rotate(360deg);
41 }
42 }
43 </style>
44</head>
45
46<body>
47 <div id="root">
48 <div class="App">
49 <p>
50 Loading...
51 </p>
52 </div>
53
54 <script>
55 if ('serviceWorker' in navigator) {
56 window.addEventListener('load', function () {
57 navigator.serviceWorker.register('service-worker.js').then(function (registration) {
58 console.log('ServiceWorker registration successful with scope: ', registration.scope);
59 }, function (err) {
60 console.log('ServiceWorker registration failed: ', err);
61 }).catch(function (err) {
62 console.log(err)
63 });
64 });
65 } else {
66 console.log('service worker is not supported');
67 }
68 </script>
69
70</body>
71
72</html>

We can now delete App.css and index.css file from out project directory and also remove their import references from App.js and index.js.

The above process improves the performance of our app by 10 points. The overall PWA score is same though:

Adding it to Device’s Home Screen

🔗

The creators of create-react-app is so good to us that they have already included a manifest.json file in public directory with some basic configuration. This feature that we are currently adding allows a user to save our PWA site page on their device's home screen. In future, if the user wish to open the app, they can do that just by using PWA as a normal application and it will open in their phone's default browser.

For this purpose, we are going to edit public/manifest.json:

1{
2 "short_name": "PWA React App",
3 "name": "Progressive React App Example",
4 "icons": [
5 {
6 "src": "logo.png",
7 "sizes": "192x192",
8 "type": "image/png"
9 },
10 {
11 "src": "logo-512.png",
12 "sizes": "512x512",
13 "type": "image/png"
14 }
15 ],
16 "start_url": "/",
17 "display": "standalone",
18 "theme_color": "#000",
19 "background_color": "#000"
20}

Let’s talk about this file a bit. The short_name is the name of app that will appear on Home Screen of device. name will appear on the splash screen. icons is important and is the main icon of our app and will appear along the short_name on home screen, just like a native mobile application. The size of the icon must be 192x192. I haven't played around with other image formats but you can. Here is the link to a dummy logo for this walkthrough we are working on. Add it to the public directory. The 512 setting is for splash screen and is a requirement in auditing process. So here is the link to download that.

Next is start_url that notifies that the app was started frome Home Screen. Below it there are three more properties. display is for the appearance of the app, and I am making theme_color and background_color to be same since I want the application to match header background.

We will now solve one of our issue in the previous audit. We are left with only some of them to resolve.

Deployment

🔗

First, let us turn the caching on. In service-worker.js edit the first line and change the existing boolean value to true.

1var doCache = true;

I will be using Firebase here for deployment since it is easy to connect it with a web/mobile application for prototyping IMO. First, in Firebase console, create a new project pwa-example-1. Now, install the firebase-tool we need to deploy our PWA app. We will be installing this dependency as a global module.

Now the CLI tool will prompt for some questions. I am adding a series of images for clarity, make sure you choose the same answers when prompted.

npm install -g firebase-tools
# then run the following commands
firebase login
firebase init

Press the Enter key for final time and you will get a success message and two firebase config files generated in your project directory: .firebaserec and firebase.json.

Now, it is time to deploy our app. From terminal run:

npm run build && firebase deploy

The above command tells create-react-app to build our project into the build/ folder, which Firebase CLI tool then deploys. Firebase CLI tool will give you back a URL, save it and open it in Chrome, and then run our Lighthouse audit for the last time. The hosting url will be similar to below:

Hosting URL: https://pwa-example-1.firebaseapp.com

This solves our main issue from starting regarding using HTTTPS over HTTP. With that, all of our issues our solved and our PWA app gets 100/100 score.

The score looks good to me for our first application. The performance bar above of our application can be improved and there are few ways to that. I will not get into that since the scope of this application is for learning purpose.

You can find the complete code at this Github repository. Go ahead to clone the repo, don’t forget to npm install once inside the project directory and then head start by trying out aforementioned PWA tips and techniques.


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.