Prompt
How do I send web push notifications from a server?
Latest observation
Oct 14, 2026
OpenAI APIWeb search: off
To send web push notifications from a server, you generally use the Web Push Protocol with VAPID keys.
High-level flow
- Client/browser subscribes to push notifications.
- Browser gives you a push subscription object.
- Your server stores that subscription.
- When you want to notify the user, your server sends a push message to the browser’s push service endpoint using the subscription data + your VAPID credentials.
- The browser receives it in a service worker and shows a notification.
What you need
1) A Service Worker on the client
This listens for incoming push events.
self.addEventListener("push", event => {
const data = event.data ? event.data.json() : {};
event.waitUntil(
self.registration.showNotification(data.title || "Notification", {
body: data.body || "",
icon: "/icon.png"
})
);
});
2) Subscription from the browser
On the client, request permission and subscribe:
const registration = await navigator.serviceWorker.register("/sw.js");
const permission = await Notification.requestPermission();
if (permission !== "granted") {
throw new Error("Notification permission denied");
}
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array("YOUR_PUBLIC_VAPID_KEY")
});
// Send subscription to your server
await fetch("/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(subscription)
});
3) Send push from your server
Most servers use a library that handles the protocol.
Example: Node.js with web-push
Install:
npm install web-push
Generate VAPID keys:
npx web-push generate-vapid-keys
Server code:
import webpush from "web-push";
webpush.setVapidDetails(
"mailto:you@example.com",
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
const subscription = /* load stored subscription from DB */;
const payload = JSON.stringify({
title: "Hello!",
body: "You have a new message."
});
await webpush.sendNotification(subscription, payload);
Important notes
- Push notifications require HTTPS (except localhost for development).
- You must keep the VAPID private key secret.
- The browser push service may return errors like
410 Gonewhen a subscription is expired; then remove that subscription from your DB. userVisibleOnly: trueis required by browsers.
If you want to build it yourself
If you don’t want a library, you’d need to:
- Generate VAPID JWTs
- Encrypt the payload using the subscription keys
- Send an HTTPS
POSTto the endpoint in the subscription - Include proper headers per the Web Push protocol
Using a library is strongly recommended.
If you want, I can give you:
- a complete Node.js example (client + server), or
- examples in Python / PHP / Go / Java.