Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

Build Your First PWA Step by Step

Turn a small web page into a working PWA in five steps: add a manifest, icons, a service worker and offline support, then test and install it on localhost.

Time to build something. In this lesson you will turn a one-page notes app into a PWA with five small files. The goal is not completeness but the whole loop: write a manifest, register a service worker, cache the files, go offline, see it still work, install it. Later chapters explain every part in depth; for now, follow along and notice the shape.

Service workers and manifests cannot run inside this page's sandbox, so the project files are shown as read-only code. Run them yourself with any static server (for example npx serve or python -m http.server 8000) and open http://localhost:8000. Two runnable stand-ins at the end let you practise the logic here.

Step 1: the page

Create index.html. It links the manifest, sets the theme color and loads the app script.

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Trail Notes</title>
  <link rel="manifest" href="/manifest.webmanifest">
  <meta name="theme-color" content="#0b6e4f">
  <link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
  <link rel="stylesheet" href="/styles.css">
</head>
<body>
  <header><h1>Trail Notes</h1></header>
  <main>
    <form id="form">
      <input id="note" placeholder="Write a note" required>
      <button>Add</button>
    </form>
    <ul id="list"></ul>
    <p id="status"></p>
  </main>
  <script src="/app.js"></script>
</body>
</html>

Two small things matter for PWAs: the viewport meta tag (without it phones render a zoomed-out desktop layout) and the theme-color meta tag, which tints the browser UI.

Step 2: the manifest

Create manifest.webmanifest:

JSON
{
  "name": "Trail Notes",
  "short_name": "Notes",
  "description": "Quick notes for the trail, offline too.",
  "start_url": "/",
  "scope": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#0b6e4f",
  "icons": [
    { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
    { "src": "/icons/icon-maskable-512.png", "sizes": "512x512",
      "type": "image/png", "purpose": "maskable" }
  ]
}

Make the two PNG icons from any image (or an SVG exported at those sizes). Chapter 2 explains each field.

Step 3: the app script and registration

app.js stores notes in localStorage (simple enough for a first project; chapter 5 upgrades to IndexedDB) and registers the service worker.

JavaScript
// app.js
const form = document.getElementById('form');
const input = document.getElementById('note');
const list = document.getElementById('list');

function load() {
  return JSON.parse(localStorage.getItem('notes') || '[]');
}
function render() {
  list.replaceChildren(...load().map((text) => {
    const li = document.createElement('li');
    li.textContent = text;
    return li;
  }));
}

form.addEventListener('submit', (event) => {
  event.preventDefault();
  localStorage.setItem('notes', JSON.stringify([...load(), input.value]));
  input.value = '';
  render();
});
render();

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then((reg) => console.log('Service worker registered, scope:', reg.scope))
      .catch((err) => console.error('Registration failed:', err));
  });
}

Step 4: the service worker

sw.js caches the shell on install and answers requests from the cache first.

JavaScript
// sw.js
const CACHE = 'trail-notes-v1';
const SHELL = ['/', '/index.html', '/styles.css', '/app.js',
               '/icons/icon.svg', '/icons/icon-192.png'];

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(SHELL)));
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
    )
  );
});

self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;
  event.respondWith(
    caches.match(event.request).then((hit) => hit || fetch(event.request))
  );
});

Don't worry if every line is not clear yet. In short: on install open a named cache and store the shell files; on activate delete old caches; on fetch return the cached copy if there is one, otherwise go to the network.

Step 5: test it

  1. Start your static server and open http://localhost:8000 in Chrome or Edge.
  2. Open DevTools, Application tab, Service workers. You should see sw.js as "activated and is running".
  3. Open Cache storage and check that trail-notes-v1 holds your files.
  4. In the Service workers section tick Offline and reload. The page still loads.
  5. Look at Manifest: it lists your icons and any problems. If everything is fine, Chrome shows an install icon in the address bar.

If a change to a file does not show up, the old service worker is still serving the old cache. In DevTools tick Update on reload while developing. Chapter 3 explains why this happens.

The offline moment, in a stand-in

The sequence "try cache, else network" can be tested without a service worker. This stand-in uses a plain object as the cache and a function as the network that fails when we say "offline".

JS Stand-in: cache first, network second

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last two lines are the whole point of a PWA: the cached page works offline, the uncached one cannot. In practice you add an offline fallback page for the failing case; the fetch-event lesson in chapter 3 shows how.

Stand-in: a manifest linter

Typos in the manifest silently disable features. This runnable stand-in checks a manifest for the problems beginners meet most often.

JS Stand-in: lint a manifest

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What you built

Without any framework you now have: an installable site (manifest and icons), a registered service worker, a cached shell and an offline-capable page. That is a complete, if basic, PWA. The next chapters improve each part: richer manifests, safer service worker updates, smarter caching strategies, background sync and push notifications.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tag links the manifest to a page?

    The manifest is linked with a link element whose rel is manifest.
  2. 2. In the sample service worker, what happens in the install event?

    install opens the cache and calls addAll with the shell file list; deleting old caches happens in activate.
  3. 3. A page works offline in DevTools but you changed styles.css and still see the old look. Why?

    Cache-first responses stay until the cache version changes; use Update on reload while developing.
  4. 4. On which origins can you test a service worker without HTTPS?

    localhost is treated as a secure context for development.

Summary

  • A basic PWA needs an HTML page, a manifest with icons, a service worker and a registration call.
  • The sample worker caches the shell on install, cleans old caches on activate and answers fetches cache-first.
  • Test with DevTools: Service workers, Cache storage, Manifest and the Offline checkbox.
  • Use localhost for development; use HTTPS in production.

Next: PWA Browser Support and DevTools