--- url: "https://web.dev/articles/push-notifications-server-codelab" titulek: "Codelab: Build a push notification server | Articles | web.dev" h1: "Codelab: Build a push notification server Stay organized with collections Save and categorize content based on your preferences." popis: "A step-by-step interactive tutorial that shows you how to build a server that manages push notification subscriptions and sends web push protocol requests to a push service." jazyk: "en" kanonicka: "https://web.dev/articles/push-notifications-server-codelab" drobecky: ["Articles", "Codelab: Build a push notification server"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-14 00:03:30" znaku: 8381 slov: 1103 kodovani: "iso-8859-2" sha256: "cb00fc3a1720ddcdcbaf257028f2fb66cc31ccecd7803a77171cc871e62d9b91" --- Codelab: Build a push notification server Stay organized with collections Save and categorize content based on your preferences. Kate Jeffreys Kayce Basques This codelab shows you, step-by-step, how to build a push notification server. By the end of the codelab you'll have a server that: Keeps track of push notification subscriptions (i.e. the server creates a new database record when a client opts in to push notifications, and it deletes an existing database record when a client opts out) Sends a push notification to a single client Sends a push notification to all subscribed clients This codelab is focused on helping you learn by doing and doesn't talk about concepts much. Check out [How do push notifications work?](/articles/push-notifications-overview#how) to learn about push notification concepts. The client code of this codelab is already complete. You'll only be implementing the server in this codelab. To learn how to implement a push notification client, check out [Codelab: Build a push notification client](/articles/push-notifications-client-codelab). Browser compatibility This codelab is known to work with in the following operating system and browser combinations: Windows: Chrome, Edge macOS: Chrome, Firefox Android: Chrome, Firefox This codelab **does not work** with the following operating systems (or operating system and browser combinations): macOS: Brave, Edge, Safari iOS Application stack The server is built on top of [Express.js](https://expressjs.com/). The [web-push](https://www.npmjs.com/package/web-push) Node.js library handles all of the push notification logic. Subscription data is written to a JSON file using [lowdb](https://www.npmjs.com/package/lowdb). You don't have to use any of these technologies to implement push notifications. We chose these technologies because they provide a reliable codelab experience. Setup Before you can get push notifications working, you need to set up your server and client with authentication keys. See [Sign your web push protocol requests](/articles/push-notifications-overview#sign) to learn why. In the terminal, run `npx web-push generate-vapid-keys`. Copy the private key and public key values. Open `.env` and update `VAPID_PUBLIC_KEY` and `VAPID_PRIVATE_KEY`. Set `VAPID_SUBJECT` to `mailto:test@test.test`. All of these values should be wrapped in double quotes. After making your updates, your `.env` file should look similar to this: `VAPID_PUBLIC_KEY="BKiwTvD9HA…" VAPID_PRIVATE_KEY="4mXG9jBUaU…" VAPID_SUBJECT="mailto:test@test.test"` Open `public/index.js`. Replace `VAPID_PUBLIC_KEY_VALUE_HERE` with the value of your public key. Manage subscriptions Your client handles most of the subscription process. The main things your server needs to do are save new push notification subscriptions and delete old subscriptions. These subscriptions are what enable you to push messages to clients in the future. Read [Subscribe the client to push notifications](/articles/push-notifications-overview#subscription) for more context about the subscription process. Save new subscription information Click **Register service worker** in the app tab. In the status box you should see a message similar to this: `Service worker registered. Scope: https://example.com` In the app tab click **Subscribe to push**. Your browser or operating system may ask if you want to let the website send you push notifications. Click **Allow** (or the equivalent phrase used by your browser or operating system). In the status box you should see a message like this: `Service worker subscribed to push. Endpoint: https://fcm.googleapis.com/fcm/send/…` Open the terminal to see the logs. You should see `/add-subscription` followed by some data. `/add-subscription` is the URL that the client sends a [POST](https://developer.mozilla.org/docs/Web/HTTP/Methods/POST) request to when it wants to subscribe to push notifications. The data that follows is the client's subscription information that you need to save. Open `server.js`. Update the `/add-subscription` route handler logic with the following code: `app.post('/add-subscription', (request, response) => { console.log('/add-subscription'); console.log(request.body); console.log(`Subscribing ${request.body.endpoint}`); db.get('subscriptions') .push(request.body) .write(); response.sendStatus(200); });` Delete old subscription information Go back to the app tab. Click **Unsubscribe from push**. Look at the logs again. You should see `/remove-subscription` followed by the client's subscription information. Update the `/remove-subscription` route handler logic with the following: `app.post('/remove-subscription', (request, response) => { console.log('/remove-subscription'); console.log(request.body); console.log(`Unsubscribing ${request.body.endpoint}`); db.get('subscriptions') .remove({endpoint: request.body.endpoint}) .write(); response.sendStatus(200); });` Send notifications As explained in [Send a push message](/articles/push-notifications-overview#send), your server doesn't actually send the push messages directly to clients. Rather, it relies on a push service to do that. Your server basically just kicks off the process of pushing messages to clients by making web service requests (web push protocol requests) to a web service (the push service) owned by the browser vendor that your user uses. Update the `/notify-me` route handler logic with the following code: `app.post('/notify-me', (request, response) => { console.log('/notify-me'); console.log(request.body); console.log(`Notifying ${request.body.endpoint}`); const subscription = db.get('subscriptions').find({endpoint: request.body.endpoint}).value(); sendNotifications([subscription]); response.sendStatus(200); });` Update the `sendNotifications()` function with the following code: `function sendNotifications(subscriptions) { // Create the notification content. const notification = JSON.stringify({ title: "Hello, Notifications!", options: { body: `ID: ${Math.floor(Math.random() * 100)}` } }); // Customize how the push service should attempt to deliver the push message. // And provide authentication information. const options = { TTL: 10000, vapidDetails: vapidDetails }; // Send a push message to each client specified in the subscriptions array. subscriptions.forEach(subscription => { const endpoint = subscription.endpoint; const id = endpoint.substr((endpoint.length - 8), endpoint.length); webpush.sendNotification(subscription, notification, options) .then(result => { console.log(`Endpoint ID: ${id}`); console.log(`Result: ${result.statusCode}`); }) .catch(error => { console.log(`Endpoint ID: ${id}`); console.log(`Error: ${error} `); }); }); }` Update the `/notify-all` route handler logic with the following code: `app.post('/notify-all', (request, response) => { console.log('/notify-all'); response.sendStatus(200); console.log('Notifying all subscribers'); const subscriptions = db.get('subscriptions').cloneDeep().value(); if (subscriptions.length > 0) { sendNotifications(subscriptions); response.sendStatus(200); } else { response.sendStatus(409); } });` Go back to the app tab. Click **Notify me**. You should receive a push notification. The title should be `Hello, Notifications!` and the body should be `ID: ` where `` is a random number. Open your app on other supported browsers or devices. Try subscribing to push notifications and then click the **Notify all** button. You should receive the same notification on all of your subscribed devices. Next steps Read [Push notifications overview](/articles/push-notifications-overview) for a deeper conceptual understanding of how push notifications work. Check out [Codelab: Build a push notification client](/articles/push-notifications-client-codelab) to learn how to build a client that requests notification permission, subscribes the device to receive push notifications, and uses a service worker to receive push messages and display the messages as notifications. Except as otherwise noted, the content of this page is licensed under the [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). For details, see the [Google Developers Site Policies](https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its affiliates. Last updated 2020-11-11 UTC.