Pushpad
Articles › Push Subscriptions, Web Push Notifications

Web Push Notifications: store the subscription in the backend / database

  • # push-api

When a user is visiting your website and subscribes to notifications, you get a push subscription, which must be stored somewhere (in a database) in order to send notifications to that user.

Here's a simple implementation:

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
  // try to subscribe the user to notifications
  serviceWorkerRegistration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: vapidPublicKey
  }).then(function(pushSubscription) {
    // send the subscription to the backend
    var data = pushSubscription.toJSON();
    fetch('https://example.com/subscriptions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
  });
});

This code snippet subscribes the user to notifications and sends the push subscription to the backend.

Your backend will need to save the subscription in the database and use it later for sending the notifications. In particular it is important to save the endpoint and the keys (p256dh and auth): the endpoint is the URL which will be used to post the notifications, while the keys are used to encrypt the payload of the notifications, so that only the browser can read them.

Usually in the database table (e.g. subscriptions) you need to add a UNIQUE constraint on the endpoint (or use it as the primary key of the table). The endpoint uniquely identifies the push subscription of a specific browser. Then for each subscription (row) you can also keep the user ID, some tags or other data that are useful for filtering the subscriptions and sending the notifications to a specific audience.

If you don't want to manage the backend yourself, you can use Pushpad, a Backend-as-a-Service for web push notifications.