Next.js PWA: Make Your App Installable and Offline-Ready (No Plugin)

Muhaymin Bin Mehmood

Muhaymin Bin Mehmood

·
10 min read
Published Sep 1, 2024
Updated Oct 9, 2026
How to create a Progressive Web App (PWA) with Next.js 14 Banner Image
15 min read
1,561 words
24 sections12 code blocks

A Progressive Web App (PWA) is a website that users can install like an app: it gets its own icon and window, and it can still show something useful when the network is down. Next.js has everything you need built in, so you don't need a plugin.

In this guide you'll add a web app manifest, a small service worker with an offline page, an install button and safe updates to a Next.js App Router project.

Tested with: Next.js 16.4, React 19.3 and Chromium 156 (via Playwright), October 2026. The code uses the App Router and works on Next.js 14 and later.

Do You Still Need next-pwa?

No. Most older tutorials, including an earlier version of this one, use the next-pwa package. Its last release (5.6.0) was in August 2022, and it doesn't fit current Next.js:

  • It works by adding a webpack config. Next.js 16 builds with Turbopack by default, so with the old config, next build stopped with this error in our test:
Bash
$ npx next build
▲ Next.js 16.4.0 (Turbopack)
  Creating an optimized production build ...
⨯ ERROR: This build is using Turbopack, with a `webpack` config and no `turbopack` config.
  • Building with next build --webpack works, but installing next-pwa added 9 high-severity warnings to npm audit in the same project.
  • Its popular example config caches every request with urlPattern: /^https?.*/, including API calls and other sites, which can show users stale or private data offline.

You have two good options: write the few files below yourself (recommended for most apps), or use Serwist, a maintained library that precaches your whole build (more on that at the end).

What Makes a Web App Installable?

Chromium browsers offer to install a site when it has:

RequirementHow this guide covers it
HTTPS (or localhost)Vercel and most hosts give you HTTPS; localhost works for testing
A web app manifest with name or short_nameapp/manifest.js
Icons of at least 192×192 and 512×512PNG files in public/
start_url and a display mode such as standaloneSet in the manifest

Chrome no longer requires a service worker to install a site, but you need one for an offline page. Safari on iOS has no install prompt; users add the app with Share → Add to Home Screen. See MDN's installability guide for every browser's rules.

Step 1: Create the Project and Icons

Bash
npx create-next-app@latest my-pwa
cd my-pwa

These are the files you'll add or change:

Bash
my-pwa/
├── app/
│   ├── layout.js
│   ├── manifest.js
│   ├── RegisterServiceWorker.jsx
│   ├── InstallButton.jsx
│   └── offline/
│       └── page.js
├── public/
│   ├── sw.js
│   ├── icon-192.png
│   ├── icon-512.png
│   └── icon-maskable-512.png
└── next.config.js

Create three PNG icons in public/: 192×192, 512×512, and a 512×512 maskable version with the logo inside the middle 80% (Android crops maskable icons into circles and other shapes). Any favicon or PWA icon generator can make them from one image.

Step 2: Add the Web App Manifest

In the App Router, a manifest.js file in app/ is all you need. Next.js serves it at /manifest.webmanifest and adds the <link rel="manifest"> tag to every page, so you don't need a _document.js (that's the Pages Router):

JavaScript
// app/manifest.js — Next.js serves this at /manifest.webmanifest
// and adds <link rel="manifest"> to every page.
export default function manifest() {
  return {
    id: "/",
    name: "My Next.js PWA",
    short_name: "MyPWA",
    description: "An installable Next.js app that works offline",
    start_url: "/",
    scope: "/",
    display: "standalone",
    background_color: "#ffffff",
    theme_color: "#0f172a",
    icons: [
      { src: "/icon-192.png", sizes: "192x192", type: "image/png" },
      { src: "/icon-512.png", sizes: "512x512", type: "image/png" },
      {
        src: "/icon-maskable-512.png",
        sizes: "512x512",
        type: "image/png",
        purpose: "maskable",
      },
    ],
  };
}
  • id gives the app a stable identity, so changing start_url later doesn't create a second app.
  • display: "standalone" opens the app in its own window without the browser's address bar.
  • theme_color colours the title bar; background_color fills the splash screen while the app starts.

In our test, Chromium's DevTools Protocol reported no manifest errors and no installability errors for this file.

Step 3: Update the Root Layout

JSX
// app/layout.js
import RegisterServiceWorker from "./RegisterServiceWorker";
import "./globals.css";

export const metadata = {
  title: "My Next.js PWA",
  description: "An installable Next.js app that works offline",
  appleWebApp: { capable: true, title: "MyPWA", statusBarStyle: "default" },
};

export const viewport = {
  themeColor: "#0f172a",
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}
        <RegisterServiceWorker />
      </body>
    </html>
  );
}
  • The theme colour goes in the viewport export; Next.js 14 and later warn if you put it in metadata.
  • appleWebApp adds the tags iOS uses when the site is added to the home screen.
  • <RegisterServiceWorker /> registers the worker from Step 5.

Step 4: Write the Service Worker

Put this file in public/sw.js so it's served from the site root. A worker only controls pages inside its own folder, so /sw.js can handle the whole site:

JavaScript
// public/sw.js
// Change VERSION when you change this file or the offline page.
const VERSION = "v1";
const CACHE = `app-${VERSION}`;
const OFFLINE_URL = "/offline";
const PRECACHE = [OFFLINE_URL, "/icon-192.png"];

self.addEventListener("install", (event) => {
  event.waitUntil(
    (async () => {
      const cache = await caches.open(CACHE);
      await cache.addAll(PRECACHE);

      // The offline page needs its CSS and JS chunks too. Their file names
      // contain a build hash, so read them from the page's HTML.
      const html = await (await cache.match(OFFLINE_URL)).text();
      const assets = [...html.matchAll(/\/_next\/static\/[^"'\s)\\]+/g)].map((m) => m[0]);
      await cache.addAll([...new Set(assets)]);

      await self.skipWaiting();
    })(),
  );
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      // Delete caches from older versions of this worker.
      const keys = await caches.keys();
      await Promise.all(
        keys.filter((key) => key.startsWith("app-") && key !== CACHE).map((key) => caches.delete(key)),
      );
      await self.clients.claim();
    })(),
  );
});

self.addEventListener("fetch", (event) => {
  const { request } = event;
  const url = new URL(request.url);

  // Leave POSTs, other sites, API routes and Next.js data requests alone.
  if (request.method !== "GET" || url.origin !== self.location.origin) return;
  if (url.pathname.startsWith("/api/")) return;

  // Pages: always try the network; show the offline page if it fails.
  if (request.mode === "navigate") {
    event.respondWith(fetch(request).catch(() => caches.match(OFFLINE_URL)));
    return;
  }

  // Build files never change under the same URL, so cache-first is safe.
  if (url.pathname.startsWith("/_next/static/")) {
    event.respondWith(
      (async () => {
        const cached = await caches.match(request);
        if (cached) return cached;
        const response = await fetch(request);
        if (response.ok) {
          const cache = await caches.open(CACHE);
          cache.put(request, response.clone());
        }
        return response;
      })(),
    );
  }
});

How it works

  • Install: caches the offline page and an icon. A Next.js page is useless without its CSS and JavaScript, and their file names change with every build, so the worker reads them from the offline page's HTML and caches them too. In our build that was 10 files.
  • Activate: deletes caches from older versions, then clients.claim() takes control of open tabs.
  • Fetch: each kind of request gets its own strategy:
RequestStrategyWhy
Page navigationsNetwork, then offline pageUsers always get fresh pages when online
/_next/static/ filesCache firstTheir URLs contain a hash, so a cached copy is never out of date
/api/ routes, POSTs, other sitesNot handledAPI data shouldn't be served stale; the browser handles them normally

When you click a Next.js <Link> while offline, the router's data request fails and Next.js falls back to a full page load, which the worker answers with the offline page. Our test confirmed this.

Step 5: Add the Offline Page and Register the Worker

The offline page is an ordinary static route, app/offline/page.js:

JSX
// app/offline/page.js
export const metadata = { title: "You're offline" };

export default function OfflinePage() {
  return (
    <main className="offline">
      <h1>You&apos;re offline</h1>
      <p>Check your connection, then reload the page.</p>
    </main>
  );
}

Register the worker from a client component:

JSX
// app/RegisterServiceWorker.jsx
"use client";

import { useEffect } from "react";

export default function RegisterServiceWorker() {
  useEffect(() => {
    // In development a caching worker serves stale code; register it only in production builds.
    if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;

    navigator.serviceWorker
      .register("/sw.js", { scope: "/", updateViaCache: "none" })
      .catch((err) => console.error("Service worker registration failed:", err));
  }, []);

  return null;
}
  • It only registers in production builds. In next dev a caching worker can keep serving old code while you edit, which is confusing.
  • updateViaCache: "none" makes the browser check /sw.js for changes on every visit instead of using its HTTP cache.

Step 6: Don't Let sw.js Be Cached

Browsers compare /sw.js byte by byte to find updates, so it must never be served from a cache:

JavaScript
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
      {
        source: "/sw.js",
        headers: [
          { key: "Content-Type", value: "application/javascript; charset=utf-8" },
          // Always check for a new worker instead of using a cached copy.
          { key: "Cache-Control", value: "no-cache, no-store, must-revalidate" },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

Step 7: Add an Install Button (Optional)

Browsers show their own install option (an icon in Chrome's address bar, or a menu item). If you want a button inside your app, listen for beforeinstallprompt:

JSX
// app/InstallButton.jsx
"use client";

import { useEffect, useState } from "react";

export default function InstallButton() {
  const [installEvent, setInstallEvent] = useState(null);
  const [isIOS, setIsIOS] = useState(false);
  const [installed, setInstalled] = useState(false);

  useEffect(() => {
    setInstalled(window.matchMedia("(display-mode: standalone)").matches);
    setIsIOS(/iPad|iPhone|iPod/.test(navigator.userAgent));

    // Chrome and Edge fire this when the app can be installed.
    const onBeforeInstall = (e) => {
      e.preventDefault(); // keep the event so our button can show the prompt
      setInstallEvent(e);
    };
    const onInstalled = () => {
      setInstalled(true);
      setInstallEvent(null);
    };
    window.addEventListener("beforeinstallprompt", onBeforeInstall);
    window.addEventListener("appinstalled", onInstalled);
    return () => {
      window.removeEventListener("beforeinstallprompt", onBeforeInstall);
      window.removeEventListener("appinstalled", onInstalled);
    };
  }, []);

  if (installed) return null;

  if (installEvent) {
    return (
      <button
        onClick={async () => {
          installEvent.prompt();
          await installEvent.userChoice; // { outcome: "accepted" | "dismissed" }
          setInstallEvent(null); // the event can only be used once
        }}
      >
        Install app
      </button>
    );
  }

  if (isIOS) {
    return <p>To install, tap Share, then &quot;Add to Home Screen&quot;.</p>;
  }

  return null;
}
JSX
// app/page.js
import InstallButton from "./InstallButton";

export default function Home() {
  return (
    <main>
      <h1>My Next.js PWA</h1>
      <InstallButton />
    </main>
  );
}
  • beforeinstallprompt only exists in Chromium browsers (Chrome, Edge, Samsung Internet), and only fires when the site is installable and not installed yet. Elsewhere, the component shows nothing, or the iOS instructions.
  • preventDefault() stops the browser's own mini prompt so you can show the prompt from your button. Each event can only be used once.
  • The button disappears in the installed app, where display-mode: standalone matches.

We tested the button with a stand-in event (headless browsers don't fire the real one): it appeared after the event, called prompt() on click, and then hid itself. See web.dev's install prompt guide for the full behaviour.

Step 8: Build and Test

Service workers only run in a production build here, so test with:

Bash
npm run build
npm start
# open http://localhost:3000

Then open Chrome DevTools → Application:

  • Manifest: shows your name, icons and any installability problems.
  • Service workers: shows /sw.js as activated and running.
  • Cache storage: shows app-v1 with the offline page and its files.
  • Offline: tick the Offline box in the Network tab and reload any page: you should see the offline page, styled.

Lighthouse no longer has a PWA category (it was removed in Lighthouse 12), so DevTools' Application panel is the place to check.

What we tested

We ran this exact code in a Next.js 16.4 production build with Playwright and Chromium 156. All 21 checks passed:

  • the manifest link and theme colour were in the page, with no manifest or installability errors;
  • the worker activated and controlled the page after a reload, with the offline page and 10 build files cached;
  • online, pages and API responses were always fresh;
  • offline, both a direct visit and a <Link> click showed the styled offline page, and an API call failed instead of returning old data;
  • after changing VERSION to "v2", the new worker took over and only the app-v2 cache was left;
  • the install button behaved as described in Step 7.

Updating Your PWA

Pages and build files update on their own: pages always come from the network, and new builds use new file names. Change VERSION in sw.js only when you change the worker itself or the offline page. The browser then installs the new worker, skipWaiting() activates it straight away, and the activate step deletes the old cache.

Common Mistakes

MistakeWhat happensFix
cache.addAll() with a URL that 404sThe whole install fails and the worker never runsPrecache only URLs that exist; test each one
Caching every request (e.g. /^https?.*/)API and private data shown stale offlineHandle only pages and /_next/static/
Cache-first for pagesUsers keep seeing old pages after you deployNetwork first for navigations
Never changing the cache nameOld files stay in storage foreverVersion the cache and delete old ones on activate
Registering the worker in next devStale code while developingRegister only in production builds
Caching sw.js over HTTPUsers don't get worker updatesCache-Control: no-cache for /sw.js
Using next-pwa with Next.js 16next build fails with a Turbopack errorUse the files in this guide or Serwist

The first one hit the earlier version of this article: its worker precached /about, /contact and icon paths that a new project doesn't have. In our test, that worker went straight to the redundant state and never activated.

Adding Push Notifications

A PWA can receive push notifications, including on iOS 16.4+ once it's added to the home screen. Our Firebase push notifications guide for Next.js covers the setup. The official Next.js PWA guide also shows push with the web-push package.

When to Use Serwist Instead

This guide keeps one offline page. If users need many pages, or the whole app, to work offline, you need to precache the full build and handle updates carefully. Serwist does that and is actively maintained, with @serwist/next for webpack builds and @serwist/turbopack for Turbopack (version 9.5 in October 2026). Follow its docs for setup.

FAQs

Does Next.js support PWAs without a plugin?

Yes. app/manifest.js creates the manifest and its link tag, and a service worker is a plain JavaScript file in public/. This guide uses no PWA package.

Is next-pwa compatible with Next.js 15 and 16?

It hasn't been updated since 2022. With Next.js 16, its webpack-based config makes the default Turbopack build fail; next build --webpack still works, but the package and its dependencies are unmaintained.

Do I need a service worker to make my site installable?

Not in current Chrome; a manifest with icons, served over HTTPS, is enough. You need a service worker for offline support and for push notifications.

Why isn't the install prompt showing?

Check DevTools → Application → Manifest for errors, make sure you're on HTTPS or localhost, and that the app isn't already installed. Chrome also waits until the user has interacted with the page. Safari and Firefox don't fire beforeinstallprompt at all.

How do I test a PWA locally?

Run npm run build and npm start, then open http://localhost:3000. Browsers treat localhost as secure, so the manifest and service worker work without HTTPS.

Why does my PWA show old content after a deploy?

Usually because the service worker serves pages cache-first, or because /sw.js itself is cached. Use network-first for pages, send Cache-Control: no-cache for /sw.js, and register with updateViaCache: "none".

Can my PWA call APIs on other domains?

Yes, with the same rules as any web page: the API must allow your origin with CORS headers. See our Fetch and CORS guide.

No comments yet. Be the first to comment!

Leave a Comment

2000 characters remaining

Related Articles

View all
Muhaymin Bin Mehmood

About Muhaymin Bin Mehmood

Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.