Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Push Notifications

Sending Push Messages

Send web push messages from your server: generate VAPID keys, payload limits, TTL, urgency and topic headers, response codes, cleanup and the service worker push event.

With subscriptions in your database, sending is a server task: build a payload, encrypt it for each subscription, sign the request with your VAPID key and POST it to the endpoint. The cryptography (RFC 8291 message encryption and RFC 8292 VAPID) is intricate, so you should always use a maintained library rather than writing it yourself. This lesson shows how libraries are used, what the options mean, how to interpret responses, and what the service worker does when a message arrives.

Generate VAPID keys once

With the Node web-push package or PHP's minishlink/web-push, keys come from a one-line command or function. Run it once, store the private key as a secret (environment variable, never in git or in front-end code) and put the public key in your front end.

Terminal
# read-only
npx web-push generate-vapid-keys

The same key pair must be used for the entire life of the subscriptions. Rotating it means every user has to subscribe again.

Sending with a library

JavaScript
// Node server (read-only)
import webpush from "web-push";

webpush.setVapidDetails(
  "mailto:[email protected]",
  process.env.VAPID_PUBLIC_KEY,
  process.env.VAPID_PRIVATE_KEY
);

async function notify(subscription, data) {
  try {
    await webpush.sendNotification(subscription, JSON.stringify(data), {
      TTL: 60 * 60,        // seconds the push service may hold it
      urgency: "normal",   // very-low | low | normal | high
      topic: "order-42",   // a newer message with the same topic replaces the old one
    });
  } catch (error) {
    if (error.statusCode === 404 || error.statusCode === 410) {
      await deleteSubscription(subscription.endpoint);
    } else {
      throw error;
    }
  }
}
PHP
// PHP with minishlink/web-push (read-only)
use Minishlink\WebPush\{WebPush, Subscription};

$webPush = new WebPush(['VAPID' => [
    'subject' => 'mailto:[email protected]',
    'publicKey' => env('VAPID_PUBLIC_KEY'),
    'privateKey' => env('VAPID_PRIVATE_KEY'),
]]);

$webPush->queueNotification(
    Subscription::create($stored->toArray()),
    json_encode(['title' => 'Order shipped', 'url' => '/orders/42']),
    ['TTL' => 3600, 'urgency' => 'normal', 'topic' => 'order-42']
);

foreach ($webPush->flush() as $report) {
    if ($report->isSubscriptionExpired()) {
        // delete $report->getEndpoint() from the database
    }
}

What the VAPID header contains

Behind the scenes the library builds a signed JSON Web Token (JWT) with three claims: aud (the origin of the push service endpoint), exp (expiry, at most 24 hours ahead) and sub (your contact). Decoding the middle part shows exactly this:

JS Reading the VAPID claims

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Options that change delivery

Header Values Effect
TTL seconds (required) How long the push service keeps the message for an offline device. 0 means deliver now or drop.
Urgency very-low, low, normal, high Hint for battery use. high can wake a sleeping phone; use it only for real emergencies and messages.
Topic up to 32 URL-safe characters A newer message with the same topic replaces one that is still waiting. Good for "3 unread" updates.

Choose TTL by how long the message stays useful. A "your driver is arriving" push is worthless after ten minutes, a newsletter can wait a day. A missing TTL is an error for most services.

Payload rules

  • The encrypted payload is at most about 4 KB (4078 bytes), so keep it small.
  • Send an identifier and a short text, not the whole record. The service worker can fetch details after it wakes.
  • Never include secrets. The payload is encrypted end to end, but the notification text appears on lock screens.

Try it: fan-out and cleanup

A realistic sender loops over many subscriptions, sends in batches and prunes dead endpoints. The stand-in service below answers with real status codes.

JS Send to everyone and prune dead subscriptions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Interpret responses like this: 201 accepted; 404 or 410 delete the subscription; 413 payload too large; 429 slow down and honor Retry-After; 5xx retry later with backoff. In production, send through a queue worker so a slow push service never blocks a web request.

The service worker side

When the message arrives the worker wakes and receives a push event. It must show a notification before the event's promise settles:

JavaScript
// sw.js (read-only)
self.addEventListener("push", (event) => {
  const data = event.data ? event.data.json() : { title: "New activity" };

  event.waitUntil(
    self.registration.showNotification(data.title, {
      body: data.body,
      icon: "/icons/icon-192.png",
      tag: data.tag,
      data: { url: data.url ?? "/" },
    })
  );
});

A push that ends without showing a notification may cause the browser to display a generic "this site was updated in the background" message instead. Always handle empty or malformed payloads with a sensible default, as the event.data ? ... : ... line does. How to design what appears is covered in notification design.

Testing push

  • Chrome DevTools, Application panel, Service Workers: the Push field lets you fire a test push event at the worker without any server.
  • Use the command line web-push send-notification with a copied subscription for an end-to-end test.
  • Test while the browser is closed and with the device offline, then reconnected, to see TTL in action.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a library for sending push?

    RFC 8291 encryption and VAPID JWT signing are easy to get subtly wrong; maintained libraries implement them.
  2. 2. A push service answers 410. What do you do?

    410 means the subscription is permanently gone.
  3. 3. What does the Topic header do?

    Only the newest message per topic is delivered if the device was offline.
  4. 4. What happens if the push handler never shows a notification?

    User-visible-only pushes must display something; browsers enforce this.

Summary

  • Use a library, a VAPID key pair created once, and keep the private key secret.
  • Set TTL, optionally Urgency and Topic; keep payloads tiny.
  • Handle statuses: delete on 404/410, back off on 429/5xx.
  • Send from a queue worker, and always show a notification in the push handler.

Next: Notification Design