Web Standards

How to Add Web Push Notifications to a Next.js App

· 14 min read

How to Add Web Push Notifications to a Next.js App
Contents

You publish a new post and want your readers to know about it. Email needs their address, and social media depends on whatever the algorithm decides to show. Web Push needs neither. The reader flips a toggle once, and from then on your notifications land on their desktop or phone, even when your site isn’t open.

Let’s see how Web Push works under the hood and how to add it to a Next.js 16 application without making a mess of the codebase.

What Web Push is#

On the browser side, Web Push is two APIs: the Push API receives messages and the Notifications API shows them. Between your server and the browser there’s a push service, and the protocol for talking to it is standardized too: message delivery in RFC 8030, payload encryption in RFC 8291 and server identification (VAPID) in RFC 8292.

Together they let a website show notifications in the user’s browser even when the site is closed, as long as the browser is running and the user has granted permission. The notifications look exactly like native system notifications.

Support is good these days. Chrome, Edge, Firefox and the other Chromium-based browsers have had it for years, on desktop and Android. Safari supports it on macOS since version 16 (2022). On iOS and iPadOS it arrived with 16.4 (2023), but only for sites the user has added to the Home Screen.

How it works#

The flow is simpler than it sounds. A user visits your website and sees a toggle like “Notify me about new posts”. When they click it:

  1. The browser shows a permission dialog.
  2. If they allow notifications, the page subscribes through the registered service worker.
  3. The browser creates a push subscription object.
  4. Your frontend sends that subscription to your backend.
  5. You store it in your database.

Later, when something happens (a new blog post, an order update, a security alert), your server sends an encrypted message to every stored subscription. The browser receives it in the service worker, and the service worker displays a system notification.

Where it makes sense#

News sites were the first to use push, but the use cases go much further. Publishing platforms send breaking news, new posts or topic-based updates. Online stores send abandoned cart reminders, price drops, flash sales, back-in-stock alerts and delivery updates. SaaS products remind users that a trial is about to expire or a profile is incomplete, and report new comments or account activity. Booking and payment systems confirm transactions and remind people of appointments. Internal dashboards and intranets can use it too. And compared to email, subscribing takes one click.

Adding Web Push to a Next.js 16 blog#

Let’s take a simple blog built with Next.js 16:

src/app/
├── (admin)
│   ├── admin
│   ├── globals.scss
│   ├── layout.jsx
│   └── layoutPage.jsx
├── (main)
│   ├── api
│   ├── globals.css
│   ├── layout.jsx
│   ├── page.jsx
│   └── posts
├── error.jsx
├── favicon.ico
└── not-found.jsx

It has a public frontend listing posts:

Demo Blog Frontend

and an admin panel to manage them:

Demo Blog Backend

We want to notify subscribed readers whenever a new post is published.

The toggle#

On the frontend we add a small component, a notification toggle.

Toggle
// src/ui/components/NotificationToggle/NotificationToggle.jsx

"use client";

import { useEffect, useState } from "react";
import { usePushNotifications, registerServiceWorker } from "@/ui/hooks/usePushNotifications";
import clsx from "clsx";
import "./NotificationToggle.scss";

export default function NotificationToggle() {
  const { isEnabled, isLoading, error, toggleNotifications, isPushSupported } = usePushNotifications();
  const [showError, setShowError] = useState( false );

  const classes = clsx( "notification-toggle-container", {
    "toggle-loading": isLoading,
  } );

  useEffect( () => {
    // Register service worker on component mount
    registerServiceWorker();
  }, [] );

  const handleToggle = async ( e ) => {
    const checked = e.target.checked;
    const success = await toggleNotifications( checked );
    
    if ( !success && checked ) {
      // Reset the toggle to off position if subscription failed
      setShowError( true );
      setTimeout( () => setShowError( false ), 5000 );
    }
  };

  // Don't render if push notifications aren't supported
  if ( !isPushSupported ) {
    return null;
  }

  return (  
    <div className={ classes }>
      <div className="notification-toggle">
        <label className="toggle-label">
          <input
            type="checkbox"
            checked={ isEnabled }
            onChange={ handleToggle }
            disabled={ isLoading }
            className="toggle-checkbox"
            aria-label="Notify me about new posts"
          />
          <span className="toggle-slider"></span>
          <span className="toggle-text">
            Notify me about new posts
          </span>
        </label>
      </div>
      
      { error && showError && (
        <div className="notification-error">
          { error }
        </div>
      ) }
    </div>
  );
}
// src/ui/components/NotificationToggle/NotificationToggle.scss

.notification-toggle-container {
  margin: 24px 0;
  padding: 16px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  backdrop-filter: blur(6px);
}

.notification-toggle {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
}

.toggle-label {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  user-select: none;

  font-size: 14px;
  line-height: 1.5;
  color: #e6e6e6;

  transition: opacity 0.2s ease;

  &:hover {
    opacity: 0.85;
  }
}

.toggle-checkbox {
  display: none;

  &:disabled ~ .toggle-slider {
    opacity: 0.4;
    cursor: not-allowed;
  }
}

.toggle-slider {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;

  background-color: #2a2a2a;
  border: 1px solid #3a3a3a;
  border-radius: 24px;

  transition: background-color 0.3s ease, border-color 0.3s ease;
  flex-shrink: 0;
  cursor: pointer;

  &::after {
    content: "";
    position: absolute;
    width: 20px;
    height: 20px;

    background-color: #ffffff;
    border-radius: 50%;
    top: 1px;
    left: 1px;

    transition: left 0.3s ease;
  }
}

.toggle-checkbox:checked ~ .toggle-slider {
  background-color: #1677ff;
  border-color: #1677ff;

  &::after {
    left: 21px;
  }
}

.toggle-text {
  font-weight: 500;
  color: #f0f0f0;
  flex: 1;
}

.toggle-loading {
  font-size: 12px;
  color: #4ea1ff;
  animation: pulse 1.5s ease-in-out infinite;
  pointer-events: none;
}

.notification-error {
  margin-top: 12px;
  padding: 10px 14px;

  background: rgba(254, 74, 73, 0.12);
  border: 1px solid rgba(254, 74, 73, 0.35);
  border-radius: 8px;

  color: #ff6b6b;
  font-size: 13px;
  line-height: 1.4;
  text-align: center;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.45;
  }
}

@media (max-width: 768px) {
  .notification-toggle-container {
    margin: 16px 0;
    padding: 14px 16px;
  }

  .toggle-label {
    flex-wrap: wrap;
  }

  .toggle-text {
    width: 100%;
    margin-top: 8px;
  }
}

.notification-toggle-container {
  &.is-processing {
    opacity: 0.35;
    pointer-events: none;
  }
}

The component relies on a custom hook, usePushNotifications. The hook detects whether the browser supports push, subscribes and unsubscribes, and tracks loading and error states. If push isn’t supported, the toggle doesn’t render at all. The part of the hook that matters is the subscription itself:

// src/ui/hooks/usePushNotifications.js (subscribe part)
const permission = await Notification.requestPermission();

if ( permission !== "granted" ) {
  return false;
}

const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe( {
  userVisibleOnly: true,
  applicationServerKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY
} );

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

userVisibleOnly: true is a promise that every push will show a visible notification. Chrome refuses to subscribe without it. applicationServerKey takes the public VAPID key (more on that next) as a Base64 string. JSON.stringify() calls the subscription’s toJSON(), which gives { endpoint, expirationTime, keys: { p256dh, auth } }, exactly what the backend stores.

VAPID keys#

Every browser hands push delivery to its vendor’s push service: Chrome to Firebase Cloud Messaging, Firefox to Mozilla’s push service, Safari to Apple’s. The endpoint in a subscription is a URL on that service. Before the service accepts a message for that endpoint, your server has to identify itself, and that’s what VAPID keys are for.

They are a public/private key pair. The public key goes to the browser during subscription (the applicationServerKey above). The private key stays on your server and signs a token sent with every push request, so the push service knows the message comes from the same server that created the subscription.

What VAPID doesn’t do is encrypt anything. The payload is encrypted with the subscription’s own p256dh and auth keys, which is why we store them, and why only that one browser can read the message.

You generate the pair once:

npx web-push generate-vapid-keys

Then store it in your environment variables:

NEXT_PUBLIC_VAPID_PUBLIC_KEY="your_public_key"
VAPID_PRIVATE_KEY="your_private_key"

Without VAPID, push services like Chrome’s and Safari’s reject your requests.

The service worker#

Push notifications need a service worker. Ours lives in public/service-worker.js:

// public/service-worker.js

const VAPID_PUBLIC_KEY = "your_public_key";

// Handle push notifications
self.addEventListener('push', (event) => {
  const data = event.data ? event.data.json() : {};
  const {
    title = "Acme Blog",
    body = "Company news, product updates, and team stories.",
    icon = "/static/logo_512x512.png",
    badge = "/static/logo-192x192.png",
    tag = "posts-new",
    url = "/",
    data: notificationData = {}
  } = data;

  const options = {
    body,
    icon,
    badge,
    tag,
    requireInteraction: true,
    data: {
      ...notificationData,
      url,
    },
    actions: [
      {
        action: 'open',
        title: 'View Post'
      },
      {
        action: 'close',
        title: 'Dismiss'
      }
    ]
  };

  event.waitUntil(
    self.registration.showNotification(title, options)
  );
});

// Handle notification clicks
self.addEventListener('notificationclick', (event) => {
  event.notification.close();

  if (event.action === 'close') {
    return;
  }

  const data = event.notification.data || {};
  const urlToOpen = data.url || '/';

  event.waitUntil(
    clients.matchAll({
      type: 'window',
      includeUncontrolled: true
    }).then((clientList) => {
   
      const existing = clientList.find(
        (client) => client.url.includes(urlToOpen) && 'focus' in client
      );

      if (existing) {
        return existing.focus();
      }

      if (clients.openWindow) {
        return clients.openWindow(urlToOpen);
      }
    })
  );
});

// Handle notification close
self.addEventListener('notificationclose', (event) => {
  // Optional: Track notification dismissals
});

The push handler unpacks the JSON payload, falls back to defaults for anything missing and shows the notification. event.waitUntil() keeps the worker alive until the notification is on screen. On click, the worker focuses a tab that already has the post open or opens a new one. Safari supports neither the action buttons nor requireInteraction, so there the user simply clicks the notification. event.action is empty in that case, and the handler opens the post as usual.

You may have noticed the VAPID_PUBLIC_KEY constant at the top. This worker never uses it. You’d need the key in the worker only to re-subscribe from a pushsubscriptionchange handler, and then it’s better not to hardcode it. Serve the worker through a Next.js route that injects the value from the environment. One catch there: a worker served from /api/... can only control pages under /api/, unless you send a Service-Worker-Allowed header or rewrite its URL to the root.

Storing subscriptions#

When the user subscribes, the frontend POSTs the subscription to a route handler:

// src/app/(main)/api/v1/notifications/subscribe/route.js

import { postPushNotificationsModel } from "@/lib/models/index";

export async function POST( request ) {
  try {
    const subscription = await request.json();

    await postPushNotificationsModel.add( [
      subscription.endpoint,
      subscription.keys.p256dh,
      subscription.keys.auth
    ] );

    return Response.json(
      { success: true, message: "Subscription stored" },
      { status: 200 }
    );
  } catch ( error ) {
    console.error( "Error storing subscription:", error );
    return Response.json(
      { error: "Failed to store subscription" },
      { status: 500 }
    );
  }
}

Unsubscribing is the mirror image:

// src/app/(main)/api/v1/notifications/unsubscribe/route.js

import { postPushNotificationsModel } from "@/lib/models/index";

export async function POST( request ) {
  try {
    const { endpoint } = await request.json();

    await postPushNotificationsModel.remove( endpoint );

    return Response.json(
      { success: true, message: "Subscription removed" },
      { status: 200 }
    );
  } catch ( error ) {
    console.error( "Error removing subscription:", error );
    return Response.json(
      { error: "Failed to remove subscription" },
      { status: 500 }
    );
  }
}

Both route handlers go through PostPushNotificationsModel, which inserts and deletes rows in the subscriptions table:


export default class PostPushNotificationsModel extends AbstractModel {

  table = "post_push_subscriptions";

   async add( values ) {   
    const sql = `
        INSERT INTO \`${ this.table }\` 
        (endpoint, p256dh, auth, created_at, is_active) 
        VALUES (?, ?, ?, NOW(), TRUE)
        ON DUPLICATE KEY UPDATE 
          auth = VALUES(auth),
          is_active = TRUE,
          created_at = NOW()
      `,
      result = await this.query( sql, values );
    return result.affectedRows;
  }

  async remove( endpoint ) {
    await this.query( `DELETE FROM \`${ this.table }\` WHERE endpoint = ? LIMIT 1`, [ endpoint ] );
  }
  
};

ON DUPLICATE KEY UPDATE makes subscribing idempotent. If the same browser subscribes twice, its row gets updated instead of the insert failing on the unique endpoint. The table itself can be as simple as this:

CREATE TABLE post_push_subscriptions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  endpoint VARCHAR(500) UNIQUE NOT NULL,
  p256dh TEXT NOT NULL,
  auth TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  is_active BOOLEAN DEFAULT TRUE
);

Subscriptions do expire. The push service then answers with HTTP 404 or 410, and the backend should catch that and deactivate the record. You’ll see that in the sending code below.

Sending the notification#

When an admin saves a post with “Notify about this post” checked,

Demo Blog Backend Edit Post

the backend calls sendWebPushNotification:

// src/lib/utils/notification/web-push.js
import webpush from "web-push";
import dbc from "@/lib/models/db";


/**
 * Truncate endpoint URL for logging
 * @param {string} endpoint - Endpoint URL to truncate
 * @param {number} length - Max length before truncation
 * @returns {string} Truncated endpoint
 */
function truncateEndpoint( endpoint, length = 50 ) {
  return endpoint.length > length 
    ? `${endpoint.substring( 0, length )}...` 
    : endpoint;
}

/**
 * Web push notification management
 */

/**
 * Initialize VAPID keys for web push
 */
export function initializeVapid() {
  webpush.setVapidDetails(
    "mailto:[email protected]",
    process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY,
    process.env.VAPID_PRIVATE_KEY
  );
}

/**
 * Build notification payload for posts
 * @param {object} post - Array of new post objects
 *
 * @returns {object} Notification configuration with payload and body
 */
function buildJobNotificationPayload( post ) {
  const baseUrl = "http://localhost:3000";
  const payload = JSON.stringify( {
    title: "New post on Acme Blog",
    body: post.title,
    icon: `${ baseUrl }/logo-192x192.png`,
    badge: `${ baseUrl }/logo-72x72.png`,
    tag: "post-new",
    url: `${ baseUrl }/posts/${ post.slug }`
  } );

  return { payload };
}

/**
 * Send notifications to all subscribers
 * @param {array} subscriptions - Array of subscription objects
 * @param {string} payload - JSON stringified notification payload
 * @returns {Promise<object>} Results summary
 */
async function sendToAllSubscribers( subscriptions, payload ) {
  const results = {
    successful: 0,
    failed: 0,
  };

  const RATE_LIMIT_DELAY_MS = 10;

  for (const subscription of subscriptions) {
    try {
      await webpush.sendNotification(
        {
          endpoint: subscription.endpoint,
          keys: {
            p256dh: subscription.p256dh,
            auth: subscription.auth,
          },
        },
        payload
      );

      results.successful++;
    } catch ( error ) {
      results.failed++;
      await handlePushError( error, subscription );
    }

    // Rate limiting
    await new Promise( ( resolve ) => setTimeout( resolve, RATE_LIMIT_DELAY_MS ) );
  }

  return results;
}

/**
 * Handle push notification errors and cleanup invalid subscriptions
 * @param {Error} error - The error object
 * @param {object} subscription - The subscription that failed
 */
async function handlePushError( error, subscription ) {
  const endpoint = subscription.endpoint;

  // Status codes indicating invalid/expired subscription
  if ( error.statusCode === 410 || error.statusCode === 404 ) {
    console.info( `Removing invalid subscription: ${truncateEndpoint( endpoint )}` );

    try {
      await dbc.query(
        `UPDATE post_push_subscriptions SET is_active = FALSE WHERE endpoint = ?`,
        [ endpoint ]
      );
    } catch ( dbError ) {
      console.error( `Failed to deactivate subscription: ${dbError.message}` );
    }
  } else {
    console.info(
      `✗ Push failed (${error.statusCode}): ${truncateEndpoint( endpoint )}`
    );
  }
}

/**
 * Send web push notifications about new posts
 * @param {object} post - Array of new post objects
 */
export async function sendWebPushNotification( post ) {
  if ( !post ) {
    console.info( "No post to notify about" );
    return;
  }

  try {
    // Initialize VAPID keys for authentication with FCM
    initializeVapid();

    // Build notification content
    const notificationData = buildJobNotificationPayload( post );

    // Fetch all active subscriptions
    const subscriptions = await dbc.query(
      `SELECT * FROM post_push_subscriptions WHERE is_active = TRUE`
    );

    if ( subscriptions.length === 0 ) {
      console.info( "No active push subscriptions found" );
      return;
    }

    console.info(
      `\nSending notifications to ${subscriptions.length} subscriber(s)...`
    );

    // Send to all subscribers
    const results = await sendToAllSubscribers(
      subscriptions,
      notificationData.payload
    );

    // Log results
    console.info( `✓ Push notifications sent: ${results.successful}/${subscriptions.length}` );

    if ( results.failed > 0 ) {
      console.info( `✗ Failed: ${results.failed}` );
    }

  } catch ( error ) {
    console.error( "Web push notification error:", error.message );    
  }
}

The function sets the VAPID details, builds the payload (title, body, icon, URL) and fetches all active subscriptions. Then it sends each one an encrypted push message, logs failures and deactivates subscriptions that came back with 404 or 410.

Two things to change before production. baseUrl is hardcoded to http://localhost:3000, so take it from an environment variable. And subscribers get their messages one at a time with a 10 ms pause in between. For a blog with a few hundred subscribers that’s fine. With tens of thousands it runs for many minutes, and you’d rather send in parallel batches or hand the job to a queue.

The heavy lifting is done by the web-push package:

npm i web-push

It encrypts the payload and signs the requests with VAPID, so you never touch the crypto yourself.

What if the subscriber’s computer is off when you send? The push service holds the message until the browser comes back online, for as long as the message’s TTL allows. web-push defaults to four weeks. For a “new post” notice that’s probably too long, so pass a shorter TTL in the options argument of sendNotification().

On the user side#

When the push arrives, the service worker picks it up and shows it through the Notifications API. The user gets a native system notification, and clicking it opens the post.

Web Push Notification

Before going to production#

Web Push is easy to abuse, and browsers have learned to push back. A few things I’d keep in mind:

  • Don’t ask for permission on page load. Ask after a meaningful interaction. Firefox (since version 72) and Safari only show the permission prompt in response to a user gesture anyway, and Chrome switches to a quieter prompt for sites where most people decline.
  • Say what the user gets. “Notify me about new posts” works better than “Enable notifications”.
  • Make unsubscribing as easy as subscribing. Here it’s the same toggle.
  • Clean up expired subscriptions, as the sending code above does.
  • Serve the site over HTTPS. The Push API works only in secure contexts (localhost counts as one, so local development is fine).
  • Validate what comes into the subscribe endpoint. As written, it stores whatever it receives, so check at least that endpoint is an HTTPS URL and both keys are present.