DEV Community

Abhay Singh Rathore
Abhay Singh Rathore

Posted on

Building a Progressive Web App from Scratch: A Step-by-Step Guide

How to Build a Fast and Efficient Progressive Web App (PWA) from Scratch

Hello, Coder buddies!

Today's blog post is all about creating Progressive Web Apps (PWAs) from scratch, a topic that's been gaining a lot of traction in the web development community. PWAs provide a native-like user experience, all while remaining relatively lightweight and not requiring installation from an app store. The most exciting part is that they can work offline!

But how do you create a PWA? Let's break down the steps, focusing on the use of specific packages and libraries that simplify this task, save time, and provide numerous benefits for us developers.

Prerequisites

To follow this guide, you'll need a basic understanding of HTML, CSS, and JavaScript. Knowledge of Node.js and Express.js is advantageous but not mandatory.

Step 1: Set Up Your Project

First, you need to set up a new project. Start by creating a new directory for your project and initialize it with npm.

mkdir my-pwa
cd my-pwa
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: Create an Express Server

We'll be using Express.js to serve our files. Install it using npm:

npm install express
Enter fullscreen mode Exit fullscreen mode

Then, create a new file called server.js and add the following code:

const express = require('express');
const app = express();

app.use(express.static('public'));

app.listen(3000, () => {
  console.log('App is listening on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

This will serve static files from a directory named public.

Step 3: Create Your App Shell

The App Shell is the minimal HTML, CSS, and JavaScript required to power the user interface of a progressive web application. In the public directory, create three files: index.html, style.css, and main.js. You can put basic boilerplate code in these files.

Step 4: Add a Web App Manifest

A web app manifest is a JSON file that tells the browser about your Progressive Web App and how it should behave when installed on the user's desktop or mobile device. Create a file named manifest.json in the public directory and add basic information about your app. Here's an example:

{
  "name": "My PWA",
  "short_name": "PWA",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#fff",
  "description": "My first Progressive Web App",
  "icons": [{
    "src": "images/icon-192x192.png",
    "sizes": "192x192",
    "type": "image/png"
  }]
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to link this file in your index.html:

<link rel="manifest" href="/manifest.json">
Enter fullscreen mode Exit fullscreen mode

Step 5: Implement a Service Worker

Service workers are at the core of PWA functionality. They allow your app to load and function correctly even when there's no internet connection.

To begin, install the sw-toolbox and sw-precache libraries:

npm install --save-dev sw-toolbox sw-precache
Enter fullscreen mode Exit fullscreen mode

These libraries are powerful tools for making service workers easy to implement.

Next, create a new file named sw.js in your public directory and add the following code:

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('my-cache').then(function(cache) {
      return cache.addAll([
        '/',
        '/index.html',
        '/style.css',
        '/main.js',
      ]);
    })
  );


});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});
Enter fullscreen mode Exit fullscreen mode

This code tells the service worker to cache the app shell on installation, and then respond with the cached files whenever they're requested.

Finally, register the service worker in your main.js file:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    console.log('Service Worker registered with scope:', registration.scope);
  }).catch(function(error) {
    console.log('Service Worker registration failed:', error);
  });
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Test Your PWA

Now you can test your PWA! Start your server with:

node server.js
Enter fullscreen mode Exit fullscreen mode

And open your app in a web browser at http://localhost:3000. Try going offline. You'll see that your app still works!

Conclusion

Building a PWA from scratch might seem intimidating, but by breaking the process down into manageable steps and utilizing powerful libraries like sw-toolbox and sw-precache, it becomes a much simpler task.

Remember, PWAs are a great way to improve user experience, so it's worth investing your time to learn how to build them. It's an exciting technology that's only going to get bigger.

Happy coding!

Top comments (0)