Swoff Swoff

Next.js

Set up Swoff with Next.js (static export mode).

Next.js

Adapter for Next.js with static export. Swoff runs client-only — server features are not used.

Create Project

npx create-next-app@latest my-app --typescript
cd my-app

Configure Static Export

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "export",
  trailingSlash: true,
};

module.exports = nextConfig;

Project Structure

my-app
├── swoff
│   ├── sw-template.js
│   ├── sw-generator.js
│   ├── sw-injector.js
│   └── swoff.d.ts
└── package.json

Entry Point

App Router (app/layout.tsx):

"use client";
import { useEffect } from "react";
import { initServiceWorker } from "../swoff/sw-injector";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  useEffect(() => {
    initServiceWorker();
  }, []);
  return (
    <html>
      <body>{children}</body>
    </html>
  );
}

Pages Router (pages/_app.tsx):

import { useEffect } from "react";
import { initServiceWorker } from "../swoff/sw-injector";

export default function App({ Component, pageProps }: any) {
  useEffect(() => {
    initServiceWorker();
  }, []);
  return <Component {...pageProps} />;
}

Add Patterns

Copy from Patterns:

  1. SW Templateswoff/sw-template.js
  2. Build Scriptswoff/sw-generator.js
  3. Client Registrationswoff/sw-injector.js
  4. TypeScript Declarationsswoff/swoff.d.ts

Output Directory

Next.js static export outputs to out/ by default. Update your swoff/sw-generator.js to write to out/:

writeFileSync(join(__dirname, "..", "out", `sw-v${pkg.version}.js`), sw);
writeFileSync(join(__dirname, "..", "out", "version.json"), JSON.stringify({ ... }));

If deploying to Vercel, the output may differ. Check your deployment platform's docs for the final output path.

Update package.json:

{
  "scripts": {
    "build": "next build && node swoff/sw-generator.js"
  }
}

Build & Test

npm version patch
npm run build

Serve the out/ directory locally to test: npx serve out.

Next Steps

On this page