I like to build tools that don’t just work — they get out of your way. My team has been in the trenches of Next.js long enough to know exactly what hurts. One of the latest things I put together is next-pwa-pack — a drop-in package that wires up full PWA support in your Next.js app without you tearing your hair out.The Backstory (aka: Why I Wrote This Thing)Every time a client mentioned “PWA support,” I braced myself.I tried existing libraries. Too much magic. Tons of config. Or just completely incompatible with App Router — which, by the way, we’ve fully adopted. I wanted:Server-side cache revalidation.App Router integration.Easy sync between tabs.Clean API for managing the cache from the backend.Instead, I ended up writing service workers by hand. Tuning cache TTLs. Dealing with update logic. Managing stale clients. Manually wiping caches every time we shipped.And don’t even get me started on users not seeing updates until they hard-refreshed. Enough was enough.I needed something dead simple, predictable, and battle-tested. So I built it.Building next-pwa-pack: What Went Into ItStep one was writing a minimal service worker:Caches HTML with TTL.Handles static assets.Works offline, like a real PWA should.Then I added a messaging system so the client could talk to the service worker — for example, to bust a cache or disable caching entirely.Next, I wrote a few scripts:Auto-copy sw.js, manifest.json, and offline.html into your project.Inject a server action called revalidatePWA that you can use anywhere (API routes, server actions, server components — take your pick).For full App Router and SSR/Edge support, I wrapped everything in a higher-order function: withPWA. One import, one call — done.I also built in tab synchronization. Because users will open your app in 3 tabs and expect them to magically update in sync. I solved that via localStorage + storage events.The result? A package that just works. No config black magic. No rewriting core parts of your app.What You Get with next-pwa-packOnce installed, you get:Service worker registration out of the box — no boilerplate.Offline fallback with a customizable offline.html.Auto-copied files you can tweak (manifest, SW, etc.).Cache control API — clear, update, disable, all programmatically.Sync between tabs — no stale content in multi-tab setups.Dev panel for real-time PWA state during local development.Server-side revalidation support via server actions, API routes, or external webhook integrations.You can grab the package here: 👉 https://github.com/dev-family/next-pwa-packWhat Happens When You Install ItThe install script auto-copies PWA boilerplate into /public:sw.js – your service worker with cache logic.offline.html – fallback page for offline mode.manifest.json – tweak it to fit your app.⚠️ Existing files won’t be overwritten — it respects your setup.If you want to trigger the copy manually:node node_modules/next-pwa-pack/scripts/copy-pwa-files.mjs# ornpx next-pwa-pack/scripts/copy-pwa-files.mjsThe server action revalidatePWA is also added to your app/actions.ts or src/app/actions.ts file depending on your folder structure:"use server";export async function revalidatePWA(urls: string[]) { const baseUrl = process.env.NEXT_PUBLIC_HOST || "http://localhost:3000"; const res = await fetch(`${baseUrl}/api/pwa/revalidate`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ urls, secret: process.env.REVALIDATION_SECRET, }), }); return res.json();}If that file doesn’t show up, you can run:node node_modules/next-pwa-pack/scripts/copy-pwa-server-actions.mjsConfiguring Your manifest.jsonAfter install, don’t forget to customize /public/manifest.json:{ "name": "My App", "short_name": "App", "description": "My amazing PWA app", "start_url": "/", "display": "standalone", "background_color": "#ffffff", "theme_color": "#000000", "icons": [ { "src": "/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" } ]}Drop your icons into public/icons/, or tweak the paths above. Nothing fancy.Quick Start: Wire It UpWrap your layout in the PWAProvider, and the magic kicks in:import { PWAProvider } from "next-pwa-pack";export default function layout({ children }) { return {children};}If you want revalidation to work from the server side, you’ll also need to update your middleware:// /middleware.tsimport { withPWA } from "next-pwa-pack/hoc/withPWA";function originalMiddleware(request) { // your logic here return response;}export default withPWA(originalMiddleware, { revalidationSecret: process.env.REVALIDATION_SECRET!, sseEndpoint: "/api/pwa/cache-events", webhookPath: "/api/pwa/revalidate",});export const config = { matcher: ["/", "/(ru|en)/:path*", "/api/pwa/:path*"],};The HOC Options:originalMiddleware: your base middleware (e.g., for i18n or auth).revalidationSecret: secret token to lock down cache revalidation.sseEndpoint: SSE stream path (change if it conflicts).webhookPath: endpoint to hit for triggering cache refresh (used by revalidatePWA).Inside the PWAProviderThe PWAProvider bundles a bunch of stuff under the hood — and you can cherry-pick components too:RegisterSWAutomatically registers the service worker (/sw.js). Handles errors gracefully. You can override the path if needed:{children}CacheCurrentPageIntercepts navigation (including SPA-style transitions), caches the current page’s HTML.SWRevalidateListenerWatches for localStorage events and triggers cache refresh across tabs.SSERevalidateListenerListens to server-sent events from the sseEndpoint. When your backend says “revalidate these URLs,” this listener makes sure clients do it.DevPWAStatusDev-only panel you can enable like this:{children}Shows:Online/offline statusCache versionUpdate availabilityOne-click tools: clear cache, unregister SW, refresh, disable/enable cacheWhat the Service Worker Actually DoesThe core sw.js handles:HTML CachingPages cached with TTL (default: 10 min — tweakable in sw.js)Auto-revalidates when TTL expiresOffline fallback if HTML is missingStatic AssetsJS, CSS, images are cached foreverOnly caches GET requestsMessaging SupportSupports these actions from the client:CACHE_CURRENT_HTMLREVALIDATE_URLDISABLE_CACHE / ENABLE_CACHESKIP_WAITINGCLEAR_STATIC_CACHEOffline ModeServes offline.html if network and cache both failTries to refresh when back onlineUsing withPWA in MiddlewareThis is where next-pwa-pack really earns its keep. It brings cache revalidation to SSR and Edge Middleware — with SSE support and all.export default withPWA(originalMiddleware, { revalidationSecret: process.env.REVALIDATION_SECRET!, sseEndpoint: "/api/pwa/cache-events", webhookPath: "/api/pwa/revalidate",});Params:originalMiddleware: your existing middleware logic (auth, i18n, etc.)revalidationSecret: so nobody else can poke your cachesseEndpoint: override if something else is using this routewebhookPath: used by the server or external systems to revalidate specific URLsReal-World Use CasesUpdating Cache After Data Changesimport { updateSWCache } from "next-pwa-pack";// After creating a blog post:const handleCreatePost = async (data) => { await createPost(data); updateSWCache(["/blog", "/dashboard"]);};Updating Cache From the Serverimport { revalidatePWA } from "../actions";await createPost(data);await revalidatePWA(["/my-page"]);Clearing Cache on Logoutimport { clearAllCache } from "next-pwa-pack";const handleLogout = async () => { await logout(); await clearAllCache(); router.push("/login");};All Client Cache Actionsimport { clearAllCache, reloadServiceWorker, updatePageCache, unregisterServiceWorkerAndClearCache, updateSWCache, disablePWACache, enablePWACache, clearStaticCache, usePWAStatus,} from "next-pwa-pack";// Examples:await clearAllCache();await reloadServiceWorker();await updatePageCache("/about");await unregisterServiceWorkerAndClearCache();await clearStaticCache();updateSWCache(["/page1", "/page2"]);disablePWACache();enablePWACache();const { online, hasUpdate, swInstalled, update } = usePWAStatus();API Route for External Cache TriggersIf you want to trigger cache refreshes externally (e.g., from an admin panel), here’s an API route you can use:// app/api/webhook/revalidate/route.tsimport { NextRequest, NextResponse } from "next/server";import { revalidatePWA } from "@/app/actions";import { revalidateTag } from "next/cache";import { FetchTags } from "@/app/api/endpoints/backend";export async function POST(request: NextRequest) { try { const { tags, secret, urls } = await request.json(); if (secret !== process.env.REVALIDATION_SECRET) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const validTags = Object.values(FetchTags); const invalidTags = tags?.filter((tag) => !validTags.includes(tag)) || []; if (invalidTags.length > 0) { return NextResponse.json( { error: `Invalid tags: ${invalidTags.join(", ")}` }, { status: 400 } ); } let successful = 0; let failed = 0; if (tags?.length) { const tagResults = await Promise.allSettled( tags.map((tag) => revalidateTag(tag)) ); successful = tagResults.filter((r) => r.status === "fulfilled").length; failed = tagResults.filter((r) => r.status === "rejected").length; } if (urls?.length) { await revalidatePWA(urls); } return NextResponse.json({ success: true, message: "Cache revalidation completed", tags, urls, successful, failed, timestamp: new Date().toISOString(), }); } catch (error) { console.error("Webhook revalidation error:", error); return NextResponse.json({ error: "Internal server error" }, { status: 500 }); }}Hit it with:POST https://your-app.com/api/webhook/revalidate{ "tags": ["faq"], "secret": "1234567890", "urls": ["/ru/question-answer"]}Debugging & DevToolsHere’s what you can check when debugging:Go to DevTools → Application → Service Workers.Confirm the worker is registered.Check Cache Storage → html-cache-v2 to see if pages are cached.Simulate offline in Network → Offline and reload. You should see offline.html.Console logs from the service worker help too:[PWA] Service Worker registered[SW] Cached: /about[SW] Revalidated and updated cache for: /blogGotchas & NotesA few things you should know before you ship:SecurityPWA requires HTTPS in production.Only GET requests are cached.Don’t cache sensitive data.PerformanceThe package doesn’t touch your app’s performance baseline.It improves repeated loads significantly.ConfigTTL is set in sw.js (default: 10 minutes).You can exclude URLs from caching via CACHE_EXCLUDE.manifest.json needs to be tailored to your app.revalidatePWA action is editable — customize it as needed.withPWA and PWAProvider both accept options:export default function PWAProvider({ children, swPath, devMode = false, serverRevalidation = { enabled: true, sseEndpoint: "/api/pwa/cache-events" },}: PWAProviderProps) {What’s Nextnext-pwa-pack is written for Next.js 15. It should work on Next.js 13 App Router as well — just not tested extensively.Planned features:TTL config via options (no editing sw.js)Push notificationsPattern-based cache controlPerformance metrics for cache efficiencyThat’s it.If you’re tired of wrangling service workers manually, give next-pwa-pack a shot. You’ll go from zero to full PWA support in one coffee break.Questions, bugs, or feedback? Open an issue or hit us up.👉 github.com/dev-family/next-pwa-pack