Articles › Pushpad, Targeting Users

Web push notifications: user log in and log out

  • # javascript-sdk
  • # push-api
  • # targeting
  • # web-notifications

How can you associate a push subscription to a specific user? How can you implement log-in and log-out for web push notifications?

When a user grants permission to receive push notifications from your website, you get a push subscription.

Then that subscription will be stored in the backend, so that you can use it to send notifications.

However a subscription alone is anonymous (and all the subscriptions are indistinguishable from each other).

So, what can you do if you want to send a notification to a specific user?

When you send the subscription to your backend and you store it, you need to attach some data to the subscription, so that you can send messages to that specific subscriber later.

If you use Pushpad it's simple to associate a user ID to the current subscription:

// subscribe the user to notifications
// and associate the ID 123 to his subscription
pushpad('subscribe', null, { uid: '123', uidSignature: '…' });

Then you can send notifications to that specific user:

notification = Pushpad::Notification.new({ body: "Hello, User 123!", })
notification.deliver_to ["123"]

You can learn more about the Javascript SDK or about the libraries for sending the notifications.

Log in

The user can also subscribe to notifications and then log in after some time.

Or it can happen that a user logs in with a different account.

In that case you can assign or update the user ID for the current push subscription with this command:

// change the user ID associated to the current browser
// it's useful after a log in for example
pushpad('uid', '987', 'mySignature');

Log out

When a user logs out from your website, you usually want to stop sending him sensitive notifications.

Basically you need to remove the user ID from the push subscription (you will need to make a call to the backend that removes the user ID associated to the push subscription).

In this way the push subscription becomes anonymous again: you can still send marketing campaigns and general notifications, but you stop sending notifications specific to the user account.

So, how can you log out the user from notifications? If you use Pushpad you can use this command:

// remove the user ID associated to the current browser
// it's useful after a log out for example
pushpad('unsubscribe', function () {}, { uid: true });


You can also read these related articles: