How to send single-user targeted notification with Web Push API

I would like to reply to an interesting question that has been posted on StackOverflow. I reply here because the original question has been deleted.

Question

Goal: There’s a WebApp which allows sending direct messages from user to user. And i’d love it to display push notification every time user receives one.


I’ve been reading a lot in a last two days about push notifications and web push API. From what i understood, there are three base layers needed to push a notification:

  • Server sending notification request
  • Push server that literally pushes messages to the clients
  • Service Worker handling message

The first and the last point are clear and easy, it’s the push server that i can’t get right.

From what i’ve read on various places, it’s not possible to (w/o huge effort) to create own Push Server.

I’ve dug through tons of Push Service providers and didn’t find any that allows me to target my push message to specific user. I’ve found filters and tags, but that just doesn’t seem to be a right thing to do. I don’t wanna filter out 7k users, i just want to send notification to one of them.

Is there anything considered to be best practice in this subject? Or is it simply not possible without writing custom Push Server?

Any kind of help (including link to article explaining the matter) will be highly appreciated.

Answer

I’ve dug through tons of Push Service providers and didn’t find any that allows me to target my push message to specific user.

You have probably missed Pushpad: it’s meant exactly for that.

First of all you need to subscribe the user to push notifications using the Javascript SDK. You can easily track the user ID when you subscribe a browser to web push:

// for example, if the current user has ID=123
pushpad('uid', '123', 'UID_SIGNATURE');
pushpad('subscribe');

You can read more about the uid signature here: https://pushpad.xyz/docs/identifying_users

Then you can easily target a single user or multiple users when you send push notifications using their uids (user IDs). There are libraries available for most languages.

For example, if you use Ruby:

notification = Pushpad::Notification.new({
  title: "Example",
  body: "Hello world!",
  target_url: "http://example.com"
  # other options...
})

# deliver to the user '123'
notification.deliver_to '123'

# or you can deliver to multiple users at once:
notification.deliver_to ['123', '456']

Leave a Reply

Your email address will not be published. Required fields are marked *