push-notificationweb-pushpush-api

Is it really necessary to update the subscription on every page load?


I'm currently working on a web app which will allow a user to subscribe to push notifications. We'll store the subscriptions in a database table mapped against the user's ID and when a notification needs to be sent, we'll look up the user's subscriptions and send the notifications.

I've been following this guide: https://developers.google.com/web/fundamentals/codelabs/push-notifications/

All is going well, but something just doesn't feel "right".

On every page load, the service worker is registered, then it checks if they're already subscribed, then even if they are it calls updateSubscriptionOnServer() which contains the following comment:

// TODO: Send subscription to application server

This effectively means that every page load is going to be attempting to write the same subscription back to the database. Obviously we'll handle that in the application, but it doesn't seem ideal.

With the Web Push API, is this the expected approach?

Many thanks


Solution

  • Yes it can be useful to send the subscription to server on every page load:

    1. The user may have changed permission from blocked to granted (or default) in the browser settings, so you want to create the subscription and send it to the server
    2. The subscription endpoint may change for different reasons, so you need to make sure that the current endpoint is sent to the server (the previous endpoint will return 410 Gone)

    A compromise between the points above and performance can be to send the subscription to the server only on given pages (e.g. homepage).