How to Build a PWA in Vanilla JS
A simple step-by-step tutorial, all done with pure JavaScript, to set up a simple PWA that can be accessed offline using a web app manifest and a service worker.

Table of Contents
- What are Progressive Web Apps?
- Setup your base app for PWA
What are Progressive Web Apps?

Learn How to Master Digital Trust

LoginRadius Product Roadmap 2025

The State of Consumer Digital ID 2024

Top CIAM Platform 2024
Today we will learn about the progressive web app, a very interesting and trending topic in current times, We will start with the basic steps first on how Progressive Web App works with vanilla js. Also, we’ll cover the concept of PWAS without using any of the frameworks, it's just a plain vanillaJS
.
What are Progressive Web Apps?
A Progressive Web app is an application which is built on top of HTML, JS and CSS with some extra features like service worker
and manifest.json
file. These extra features will give the ability to run the web application offline.
Various big companies are moving towards the progressive web app instead of native apps, as it gives some much flexibility to end-users. In some websites you can find the + icon at the right side of the address bar, those are progressive web apps.
Setup your base app for PWA
We will be using npm
to start our project, so firstly create a root folder using this command mkdir first-pwa-app
or another name of your choice then go to that directory by using this command cd first-pwa-app
. Run npm init
1npm init
2package name: (first-pwa-app)
3version: (1.0.0)
4description: This is the first PWA example
5entry point: (index.js): index.html
6test command:
7git repository:
8keywords:
9author: Mohammed Modi
10license: (ISC)
Once you fill up those details your final output of the package.json
file will be below
1{
2 "name": "first-pwa-app",
3 "version": "1.0.0",
4 "description": "This is the first PWA example",
5 "main": "index.html",
6 "scripts": {
7 "test": "echo \"Error: no test specified\" && exit 1"
8 },
9 "author": "Mohammed Modi",
10 "license": "ISC"
11}
After that, we need to install the serve
dependency to serve the application in localhost so install it using npm npm i serve --save
. And then add a script in the package.json
file.
1{
2 ...
3 "scripts": {
4 "test": "echo \"Error: no test specified\" && exit 1",
5 "serve": "serve ."
6 },
7 ...
8}
So finally our application is ready to serve in localhost. Now let's add some html
and css
Setting up the Javascript
Create a directory for the app and add js, css, and images subdirectories. It should look like this when you’re finished:
1/first-pwa-app # Project Folder
2 /css # Stylesheets
3 /js # Javascript
4 /images # Image files.
5 package.json
6 package-lock.json
7 index.html
8 manifest.json
9 sw.js
You will understand the use of manifest.json
and sw.js
files once we move ahead in this tutorial.
Add Some code for app interface
When writing the code for Progressive Web Application we need to keep in mind two requirements
- The landing page should have some content even if the javascript is not loaded
- The App should be responsive and can be properly interactive in any device.
For this app, to handle the first requirement we will add the static text in the Html page and for the second requirement, we will use the viewport.
So let's add this code inside the index.html
file.
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8" />
5 <title>My First PWA</title>
6 <link rel="stylesheet" href="css/style.css" />
7 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
8 </head>
9 <body class="fullscreen">
10 <div class="container">
11 <h1 class="title">My First PWA!</h1>
12 </div>
13 </body>
14</html>
Next, we need to create a file css/style.css
and paste this code inside this
1body {
2 font-family: sans-serif;
3}
4/* Make content area fill the entire browser window /
5/ Make content area fill the entire browser window */
6html,
7.fullscreen {
8display: flex;
9height: 100%;
10margin: 0;
11padding: 0;
12width: 100%;
13}
14/* Center the content in the browser window */
15.container {
16margin: auto;
17}
18.title {
19font-size: 3rem;
20}
Once you add the code save all the files and run the script npm run serve
which will start your application in http://localhost:5000/
Testing the App
As we can see our application is running in the browser, let test it using the LightHouse Extension in Google Chrome browser. For the best result, I recommend testing in an incognito tab of google chrome.
As you can see we have green signals for both of our above requirement:
- Has a tag with width or initial-scale
- Contains some content when JavaScript is not available
But still, there is lots of work to do, so let's start with the first feature of PWA's.
Adding a Web App Manifest
Let's create a new file called manifest.json
in the root of our application. To understand more about the manifest file check out [this doc]
1{
2 "name": "My First Progressive Web app",
3 "short_name": "First PWA",
4 "lang": "en-US",
5 "start_url": "/index.html",
6 "display": "standalone",
7 "background_color": "white",
8 "theme_color": "white"
9}
Now update the index.html
head tag by adding the manifest.json file as a link
1<head>
2 ...
3 <link rel="manifest" href="/manifest.json" />
4 ...
5</head>
We should also declare the theme colour which should match with your manifest.json file as meta tag
.
1<head>
2 ...
3 <meta name="theme-color" content="white" />
4 ...
5</head>
Once you run the lighthouse test again you can see we got green signals in some points like
- Sets a theme colour for the address bar.
App Icons
Still, we need to add more attributes to our manifest.json
files like icons so let's add the icons inside the images
folder, I have used to icons pwa-icon-256.webp
and pwa-icon-256.webp
for this demo you can find in this repo. You can use various sizes in it. And finally, add the favicon.webp
in the root of the project.
So let's add the icons
attribute after the short-name
1{
2 "name": "My First Progressive Web app",
3 "short_name": "First PWA",
4 "icons": [
5 {
6 "src": ".images/pwa-icon-256.webp",
7 "sizes": "256x256",
8 "type": "image/png"
9 },
10 {
11 "src": ".images/pwa-icon-512.webp",
12 "sizes": "512x512",
13 "type": "image/png"
14 }
15 ],
16 "lang": "en-US",
17 "start_url": "/index.html",
18 "display": "standalone",
19 "background_color": "white",
20 "theme_color": "white"
21}
And the index.html will head can will look like
1<head>
2 ...
3 <link rel="apple-touch-icon" href="images/pwa-icon-256.webp" />
4 ...
5</head>
You can also verify the manifest.json
file by opening Chrome DevTools, in the Application Tab, the first tab in the sidebar manifest
After running the test again, we can see all the manifest.json
related issues are solved, The remaining issues can be resolved by adding the service worker.
Adding Service Worker
The next requirement of our app will be the service worker. The service worker is a script that runs in the background without any user interaction.
The task of service worker will be to download and cache our content and then serve it when the user is offline. To understand more on service workers you can check this doc from mozilla.
To integrate service workers we need to create a file called sw.js
in the root of our project.
Note: Service worker will only have the access to the files of the current and sub-directories hence we need to place it in the root of our project
1let cacheName = "my-first-pwa";
2let filesToCache = ["/", "/index.html", "/css/style.css", "/js/main.js"];
3/* Start the service worker and cache all of the app's content */
4self.addEventListener("install", (e) => {
5e.waitUntil(
6caches.open(cacheName).then(function (cache) {
7return cache.addAll(filesToCache);
8})
9);
10});
11/* Serve cached content when offline */
12self.addEventListener("fetch", (e) => {
13e.respondWith(
14caches.match(e.request).then((response) => {
15return response || fetch(e.request);
16})
17);
18});
The first 2 variables cacheName
and filesToCache
are used to create an offline cache in the browser. cacheName
is used to create a cache of specific name and filesToCache
will be the list of files that we need to cache, /
will store the root files that is index.html
even if the user does not specify the file name in the URL and then all other files specified in the array.
Note: Here I have used the
filesToCache
array as a list of static files just to demonstrate the purpose of PWA, it will stop working in production if even one file fails to load.
Finally, we will load our service worker, for that create js/main.js
file and copy the below code.
1window.onload = () => {
2 "use strict";
3if ("serviceWorker" in navigator) {
4navigator.serviceWorker.register("./sw.js");
5}
6};
And add this script in the index.html
file.
1...
2<script src="js/main.js"></script>
So the final version of our index.html
file will look like:
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="utf-8" />
5 <title>Hello World</title>
6 <link rel="apple-touch-icon" href="images/pwa-icon-256.webp" />
7 <link rel="stylesheet" href="css/style.css" />
8 <link rel="manifest" href="/manifest.json" />
9 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
10 <meta name="theme-color" content="white" />
11 </head>
12 <body class="fullscreen">
13 <div class="container">
14 <h1 class="title">Hello World!</h1>
15 </div>
16 <script src="js/main.js"></script>
17 </body>
18</html>
Now our application is made as fully PWA supported, you can verify it by running the lighthouse test.
Finishing Up
We are done with the code, now the last thing remaining in to host it in any of the https
domain. As the PWA will be required to run in the secure domain.
You can get the full source code of this example in this Github repo
I hope you enjoyed the progressive web apps using vanilla js tutorial and found it useful. Please let me know what you think in the comments below.

Featured Posts
TOTP Authentication Explained: How It Works, Why It’s Secure
Advantages of Time-Based One-Time Passwords (TOTP)
JWT Authentication with LoginRadius: Quick Integration Guide
Complete Guide to JSON Web Token (JWT) and How It Works
A comprehensive guide to OAuth 2.0
How Chrome’s Third-Party Cookie Restrictions Affect User Authentication?
How to Implement OpenID Connect (OIDC) SSO with LoginRadius?
Testing Brute-force Lockout with LoginRadius
Breaking Down the Decision: Why We Chose AWS ElastiCache Over Redis Cloud
LoginRadius Launches a CLI for Enterprise Dashboard
How to Implement JWT Authentication for CRUD APIs in Deno
Multi-Factor Authentication (MFA) with Redis Cache and OTP
Introduction to SolidJS
Why We Re-engineered LoginRadius APIs with Go?
Why B2B Companies Should Implement Identity Management
Top 10 Cyber Threats in 2022
Build a Modern Login/Signup Form with Tailwind CSS and React
M2M Authorization: Authenticate Apps, APIs, and Web Services
Implement HTTP Streaming with Node.js and Fetch API
NestJS: How to Implement Session-Based User Authentication
How to Integrate Invisible reCAPTCHA for Bot Protection
How Lapsus$ Breached Okta and What Organizations Should Learn
NestJS User Authentication with LoginRadius API
How to Authenticate Svelte Apps
How to Build Your Github Profile
Why Implement Search Functionality for Your Websites
Flutter Authentication: Implementing User Signup and Login
How to Secure Your LoopBack REST API with JWT Authentication
When Can Developers Get Rid of Password-based Authentication?
4 Ways to Extend CIAM Capabilities of BigCommerce
Node.js User Authentication Guide
Your Ultimate Guide to Next.js Authentication
Local Storage vs. Session Storage vs. Cookies
How to Secure a PHP API Using JWT
React Security Vulnerabilities and How to Fix/Prevent Them
Cookie-based vs. Cookieless Authentication: What’s the Future?
Using JWT Flask JWT Authentication- A Quick Guide
Single-Tenant vs. Multi-Tenant: Which SaaS Architecture is better for Your Business?
Build Your First Smart Contract with Ethereum & Solidity
What are JWT, JWS, JWE, JWK, and JWA?
How to Build an OpenCV Web App with Streamlit
32 React Best Practices That Every Programmer Should Follow
How to Build a Progressive Web App (PWA) with React
Bootstrap 4 vs. Bootstrap 5: What is the Difference?
JWT Authentication — Best Practices and When to Use
What Are Refresh Tokens? When & How to Use Them
How to Participate in Hacktoberfest as a Maintainer
How to Upgrade Your Vim Skills
Hacktoberfest 2021: Contribute and Win Swag from LoginRadius
How to Implement Role-Based Authentication with React Apps
How to Authenticate Users: JWT vs. Session
How to Use Azure Key Vault With an Azure Web App in C#
How to Implement Registration and Authentication in Django?
11 Tips for Managing Remote Software Engineering Teams
One Vision, Many Paths: How We’re Supporting freeCodeCamp
C# Init-Only Setters Property
Content Security Policy (CSP)
Implementing User Authentication in a Python Application
Introducing LoginRadius CLI
Add Authentication to Play Framework With OIDC and LoginRadius
React renderers, react everywhere?
React's Context API Guide with Example
Implementing Authentication on Vue.js using JWTtoken
How to create and use the Dictionary in C#
What is Risk-Based Authentication? And Why Should You Implement It?
React Error Boundaries
Data Masking In Nginx Logs For User Data Privacy And Compliance
Code spliting in React via lazy and suspense
Implement Authentication in React Applications using LoginRadius CLI
What is recoil.js and how it is managing in react?
How Enum.TryParse() works in C#
React with Ref
Implement Authentication in Angular 2+ application using LoginRadius CLI in 5 mins
How Git Local Repository Works
How to add SSO for your WordPress Site!
Guide to Authorization Code Flow for OAuth 2.0
Introduction to UniFi Ubiquiti Network
The Upcoming Future of Software Testers and SDETs in 2021
Why You Need an Effective Cloud Management Platform
What is Adaptive Authentication or Risk-based Authentication?
Top 9 Challenges Faced by Every QA
Top 4 Serverless Computing Platforms in 2021
QA Testing Process: How to Deliver Quality Software
How to Create List in C#
What is a DDoS Attack and How to Mitigate it
How to Verify Email Addresses in Google Sheet
Concurrency vs Parallelism: What's the Difference?
35+ Git Commands List Every Programmer Should Know
How to do Full-Text Search in MongoDB
What is API Testing? - Discover the Benefits
The Importance of Multi-Factor Authentication (MFA)
Optimize Your Sign Up Page By Going Passwordless
Image Colorizer Tool - Kolorizer
PWA vs Native App: Which one is Better for you?
How to Deploy a REST API in Kubernetes
Integration with electronic identity (eID)
How to Work with Nullable Types in C#
Git merge vs. Git Rebase: What's the difference?
How to Install and Configure Istio
How to Perform Basic Query Operations in MongoDB
Invalidating JSON Web Tokens
How to Use the HTTP Client in GO To Enhance Performance
Constructor vs getInitialState in React
Web Workers in JS - An Introductory Guide
How to Use Enum in C#
How to Migrate Data In MongoDB
A Guide To React User Authentication with LoginRadius
WebAuthn: A Guide To Authenticate Your Application
Build and Push Docker Images with Go
Istio Service Mesh: A Beginners Guide
How to Perform a Git Force Pull
NodeJS Server using Core HTTP Module
How does bitwise ^ (XOR) work?
Introduction to Redux Saga
React Router Basics: Routing in a Single-page Application
How to send emails in C#/.NET using SMTP
How to create an EC2 Instance in AWS
How to use Git Cherry Pick
Password Security Best Practices & Compliance
Using PGP Encryption with Nodejs
Python basics in minutes
Automating Rest API's using Cucumber and Java
Bluetooth Controlled Arduino Car Miniature
AWS Services-Walkthrough
Beginners Guide to Tweepy
Introduction to Github APIs
Introduction to Android Studio
Login Screen - Tips and Ideas for Testing
Introduction to JAMstack
A Quick Look at the React Speech Recognition Hook
IoT and AI - The Perfect Match
A Simple CSS3 Accordion Tutorial
EternalBlue: A retrospective on one of the biggest Windows exploits ever
Setup a blog in minutes with Jekyll & Github
What is Kubernetes? - A Basic Guide
Why RPA is important for businesses
Best Hacking Tools
Three Ways to do CRUD Operations On Redis
Traversing the realms of Quantum Network
How to make a telegram bot
iOS App Development: How To Make Your First App
Apache Beam: A Basic Guide
Python Virtual Environment: What is it and how it works?
End-to-End Testing with Jest and Puppeteer
Speed Up Python Code
Build A Twitter Bot Using NodeJS
Visualizing Data using Leaflet and Netlify
STL Containers & Data Structures in C++
Secure Enclave in iOS App
Optimal clusters for KMeans Algorithm
Upload files using NodeJS + Multer
Class Activation Mapping in Deep Learning
Full data science pipeline implementation
HTML Email Concept
Blockchain: The new technology of trust
Vim: What is it and Why to use it?
Virtual Dispersive Networking
React Context API: What is it and How it works?
Breaking down the 'this' keyword in Javascript
Handling the Cheapest Fuel- Data
GitHub CLI Tool ⚒
Lazy loading in React
What is GraphQL? - A Basic Guide
Exceptions and Exception Handling in C#
Unit Testing: What is it and why do you need it?
Golang Maps - A Beginner’s Guide
LoginRadius Open Source For Hacktoberfest 2020
JWT Signing Algorithms
How to Render React with optimization
Ajax and XHR using plain JS
Using MongoDB as Datasource in GoLang
Understanding event loop in JavaScript
LoginRadius Supports Hacktoberfest 2020
How to implement Facebook Login
Production Grade Development using Docker-Compose
Web Workers: How to add multi-threading in JS
Angular State Management With NGXS
What's new in the go 1.15
Let’s Take A MEME Break!!!
PKCE: What it is and how to use it with OAuth 2.0
Big Data - Testing Strategy
Email Verification API (EVA)
Implement AntiXssMiddleware in .NET Core Web
Setting Up and Running Apache Kafka on Windows OS
Getting Started with OAuth 2.0
Best Practice Guide For Rest API Security | LoginRadius
Let's Write a JavaScript Library in ES6 using Webpack and Babel
Cross Domain Security
Best Free UI/UX Design Tools/Resources 2020
A journey from Node to GoLang
React Hooks: A Beginners Guide
DESIGN THINKING -A visual approach to understand user’s needs
Deep Dive into Container Security Scanning
Different ways to send an email with Golang
Snapshot testing using Nightwatch and mocha
Qualities of an agile development team
IAM, CIAM, and IDaaS - know the difference and terms used for them
How to obtain iOS application logs without Mac
Benefits and usages of Hosts File
React state management: What is it and why to use it?
HTTP Security Headers
Sonarqube: What it is and why to use it?
How to create and validate JSON Web Tokens in Deno
Cloud Cost Optimization in 2021
Service Mesh with Envoy
Kafka Streams: A stream processing guide
Self-Hosted MongoDB
Roadmap of idx-auto-tester
How to Build a PWA in Vanilla JS
Password hashing with NodeJS
Introduction of Idx-Auto-Tester
Twitter authentication with Go Language and Goth
Google OAuth2 Authentication in Golang
LinkedIn Login using Node JS and passport
Read and Write in a local file with Deno
Build A Simple CLI Tool using Deno
Create REST API using deno
Automation for Identity Experience Framework is now open-source !!!
Creating a Web Application using Deno
Hello world with Deno
Facebook authentication using NodeJS and PassportJS
StackExchange - The 8 best resources every developer must follow
OAuth implementation with Node.js and Github
NodeJS and MongoDB application authentication by JWT
Working with AWS Lambda and SQS
Google OAuth2 Authentication in NodeJS - A Guide to Implementing OAuth in Node.js
Custom Encoders in the Mongo Go Driver
React's Reconciliation Algorithm
NaN in JavaScript: An Essential Guide
SDK Version 10.0.0
Getting Started with gRPC - Part 1 Concepts
Introduction to Cross-Site Request Forgery (CSRF)
Introduction to Web Accessibility with Semantic HTML5
JavaScript Events: Bubbling, Capturing, and Propagation
3 Simple Ways to Secure Your Websites/Applications
Failover Systems and LoginRadius' 99.99% Uptime
A Bot Protection Overview
OAuth 1.0 VS OAuth 2.0
Azure AD as an Identity provider
How to Use JWT with OAuth
Let's Encrypt with SSL Certificates
Encryption, Hashing & Salting: Your Guide to Secure Data
What is JSON Web Token
Understanding JSONP
Using NuGet to publish .NET packages
How to configure the 'Actions on Google' console for Google Assistant
Creating a Google Hangout Bot with Express and Node.js
Understanding End Of Line: The Power of Newline Characters
Cocoapods : What It Is And How To Install?
Node Package Manager (NPM)
Get your FREE SSL Certificate!
jCenter Dependencies in Android Studio
Maven Dependency in Eclipse
Install Bootstrap with Bower
Open Source Business Email Validator By Loginradius
Know The Types of Website Popups and How to Create Them
Javascript tips and tricks to Optimize Performance
Learn How To Code Using The 10 Cool Websites
Personal Branding For Developers: Why and How?
Wordpress Custom Login Form Part 1
Is Your Database Secured? Think Again
Be More Manipulative with Underscore JS
Extended LinkedIn API Usage
Angular Roster Tutorial
How to Promise
Learning How to Code
Delete a Node, Is Same Tree, Move Zeroes
CSS/HTML Animated Dropdown Navigation
Part 2 - Creating a Custom Login Form
Website Authentication Protocols
Nim Game, Add Digits, Maximum Depth of Binary Tree
The truth about CSS preprocessors and how they can help you
Beginner's Guide for Sublime Text 3 Plugins
Displaying the LoginRadius interface in a pop-up
Optimize jQuery & Sizzle Element Selector
Maintain Test Cases in Excel Sheets
Separate Drupal Login Page for Admin and User
How to Get Email Alerts for Unhandled PHP Exceptions
ElasticSearch Analyzers for Emails
Social Media Solutions
Types of Authentication in Asp.Net
Using Facebook Graph API After Login
Hi, My Name is Darryl, and This is How I Work
Beginner's Guide for Sublime Text 3
Social Network Branding Guidelines
Index in MongoDB
How to ab-USE CSS2 sibling selectors
Customize User Login, Register and Forgot Password Page in Drupal 7
Best practice for reviewing QQ app
CSS3 Responsive Icons
Write a highly efficient python Web Crawler
Memcached Memory Management
HTML5 Limitation in Internet Explorer
What is an API
Styling Radio and Check buttons with CSS
Configuring Your Social Sharing Buttons
Shopify Embedded App
API Debugging Tools
Use PHP to generate filter portfolio
Password Security
Loading spinner using CSS
RDBMS vs NoSQL
Cloud storage vs Traditional storage
Getting Started with Phonegap
Animate the modal popup using CSS
CSS Responsive Grid, Re-imagined
An Intro to Curl & Fsockopen
Enqueuing Scripts in WordPress
How to Implement Facebook Social Login
GUID Query Through Mongo Shell
Integrating LinkedIn Social Login on a Website
Social Provider Social Sharing Troubleshooting Resources
Social Media Colors in Hex
W3C Validation: What is it and why to use it?
A Simple Popup Tutorial
Hello developers and designers!