Web push in Next.js

Add web push to a Next.js App Router project: a service worker in public, a client component that subscribes, and route handlers that store subscriptions and send.

Updated

Web push in a Next.js App Router project needs four things: VAPID keys in environment variables, a service worker file in public/, a client component that asks permission and subscribes, and server code that stores subscriptions and sends messages with the web-push package. The sending code must run on the Node.js runtime, so a fully static export cannot do it on its own.

1. Install and create keys

npm install web-push
npm install --save-dev @types/web-push
npx web-push generate-vapid-keys

Put the keys in .env.local:

NEXT_PUBLIC_VAPID_PUBLIC_KEY=<your public key>
VAPID_PRIVATE_KEY=<your private key>

Only variables prefixed with NEXT_PUBLIC_ reach the browser, which is what you want: the public key is exposed and the private key is not. See VAPID keys explained.

2. Add the service worker

Files in public/ are served from the site root, so public/sw.js is available at /sw.js and can control the whole site.

// public/sw.js
self.addEventListener('push', (event) => {
  const data = event.data ? event.data.json() : {};
  event.waitUntil(
    self.registration.showNotification(data.title ?? 'New message', {
      body: data.body,
      data: { url: data.url ?? '/' },
    })
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil(clients.openWindow(event.notification.data.url));
});

3. Subscribe from a client component

'use client';

import { urlBase64ToUint8Array } from '@/lib/vapid';

export function EnablePushButton() {
  async function enable() {
    if (!('serviceWorker' in navigator) || !('PushManager' in window)) return;

    const permission = await Notification.requestPermission();
    if (permission !== 'granted') return;

    const registration = await navigator.serviceWorker.register('/sw.js');
    await navigator.serviceWorker.ready;

    const subscription = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(
        process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY as string
      ),
    });

    await fetch('/api/push/subscribe', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(subscription),
    });
  }

  return <button onClick={enable}>Enable notifications</button>;
}

The permission request sits inside the click handler because Safari and Firefox require a user gesture. Put the urlBase64ToUint8Array helper from the VAPID guide in lib/vapid.ts.

4. Store the subscription

// app/api/push/subscribe/route.ts
import type { PushSubscription } from 'web-push';
import { saveSubscription } from '@/lib/subscriptions';

export async function POST(request: Request) {
  const subscription = (await request.json()) as PushSubscription;
  await saveSubscription(subscription);
  return Response.json({ ok: true });
}

saveSubscription is your own code. Store the endpoint and both keys in your database, keyed by endpoint, and validate the body before trusting it.

5. Send a notification

// lib/push.ts
import webpush, { WebPushError, type PushSubscription } from 'web-push';
import { deleteSubscription } from '@/lib/subscriptions';

webpush.setVapidDetails(
  'mailto:you@example.com',
  process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY as string,
  process.env.VAPID_PRIVATE_KEY as string
);

export async function sendPush(
  subscription: PushSubscription,
  payload: { title: string; body: string; url: string }
) {
  try {
    await webpush.sendNotification(subscription, JSON.stringify(payload));
  } catch (error) {
    if (
      error instanceof WebPushError &&
      (error.statusCode === 404 || error.statusCode === 410)
    ) {
      await deleteSubscription(subscription.endpoint);
      return;
    }
    throw error;
  }
}

Call sendPush from a route handler, a server action or a background job. A 404 or 410 from the push service means the subscription has expired or been removed, so delete it.

Things to watch

  • Runtime. web-push depends on Node.js APIs. Keep the code that imports it on the default Node.js runtime, not the Edge runtime.
  • Static export. With output: 'export' there is no server to receive subscriptions or send messages. Host those endpoints elsewhere.
  • Protect the send path. Never expose an unauthenticated endpoint that sends notifications.
  • iPhone and iPad. Push only works there for an installed Home Screen web app. See Safari push setup.

For the concepts behind the code, read how web push works.