Making React App a Progressive Web App (PWA)
Tags: react, pwa, programming, webdev
Published: 2021-01-10 05:52:24

# What is a PWA?
Progressive Web Apps are user experiences that have the reach of the web, and are:

**Reliable** - Load instantly and never show the down sour, even in uncertain network conditions.
**Fast** - Respond quickly to user interactions with silky smooth animations and no janky scrolling.
**Engaging** - Feel like a natural app on the device, with an immersive user experience.

This new level of quality allows Progressive Web Apps to earn a place on the user's home screen.

# 1. Register a Service Worker
**What is a service worker?**
Service workers (client-side proxies that pre-cache key resources) enable PWAs to load instantly and provide an instant,
reliable experience for users, regardless of the network state.

Create a new `worker.js` file in the public folder **(public/worker.js)** and add the following code:

```javascript
Let CACHE_NAME = 'your-app-name';
Let urlsToCache = [
  '/',
  '/completed'
];

// Install a service worker
self.addEventListener('install', event => {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

// Cache and return requests
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});

// Update a service worker
self.addEventListener('activate', event => {
  Let cacheWhitelist = ['your-app-name'];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});
```

Note! from above code replace (your-app-name) with your app name

# 2. Now Update HTML
Update your `index.html` file in the public folder **(public/index.html)**
to check if the client’s browser supports service workers. Just Add below code inside the body tag of your app's **(public/index.html)**

```javascript
<script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('worker.js').then(function(registration) {
            console.log('Worker registration successful', registration.scope);
          }, function(err) {
            console.log('Worker registration failed', err);
          }).catch(function(err) {
            console.log(err);
          });
        });
      } else {
        console.log('Service Worker is not supported by browser.');
      }
    </script>
```

# 3. Activating ServiceWorker
Now go to your app's index.js in the src folder **(src/index.js)**

Now Update `serviceWorker.unregister()` to `serviceWorker.register()` Like Below Code At Last Line

```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.register();
```
Restart (npm start) and reload your React app — you should see the message “Worker registration successful” in the console.

# 4. Create a manifest.json file
Manifest is a simple JSON file that tells the browser about your web application and how it should behave when 'installed' on the user's mobile device or desktop. Having a manifest is required by Chrome to show the Add to Home Screen prompt.

A typical manifest file includes information about the app name, icons it should use, the start_url it should start at when launched, and more.

```javascript
{
    "name": "your-app-name",
    "short_name": "your-app-name",
    "icons": [
        {
            "src": "img/logo.png",
            "sizes": "92x92",
            "type": "image/png"
        },
        {
            "src": "/img/logo.png",
            "sizes": "144x144",
            "type": "image/png"
        },
        {
            "src": "img/logo.png",
            "sizes": "152x152",
            "type": "image/png"
        }        
    ],
    "start_url": "/",
    "display": "standalone",
    "orientation": "portrait",
    "background_color": "#f0f2f5",
    "theme_color": "#96f2d7"
}
```

### That's it 🎉 Congratulations, you just created a working progressive web app!
### Give The heart ❤️ To Appreciate My Work And Follow Me For More Awesome Content.
### This Is "Ankit Kamboj"

### Check Out React PWA Demo: https://im.ankitkamboj.in/