Jonathan Bennett

Set Up Push Notifications in Rails: Part 1

With SSL set up, let’s dive into setting up push notifications!

The web-push gem will handle the heavy lifting, including creating keys and securely communicating with third-party push notification servers. Setting up web-push involves five steps. We’ll cover the first three today:

  1. Add the web-push gem.
  2. Generate secret keys.
  3. Add a service worker to receive notifications on the client.
  4. Add frontend JavaScript to manage the subscription lifecycle.
  5. Add a backend model to store subscriptions.

Step 1: Add the web-push Gem

Add the web-push gem to your project by running: bundle add web-push

Step 2: Generate Secret Keys

Generate your secret keys using the Rails console:

# rails c
key = WebPush.generate_key
key.private_key # Copy this to your ENV variables as VAPID_PRIVATE
key.public_key # Copy this to your ENV variables as VAPID_PUBLIC

Store these keys securely in your environment variables.

Step 3: Add a Service Worker

Rails 8 includes a service worker! Enable it by uncommenting this line in config/routes.rb:

# config/routes.rb
get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker

Next, customize the service worker in app/views/pwa/service-worker.js. Here’s a simple example that handles incoming push notifications:

self.addEventListener("push", async (event) => {
	const { title, options } = await event.data.json();
	event.waitUntil(self.registration.showNotification(title, options));
});

This sets up much of the necessary infrastructure. In the next email, we’ll tackle the frontend JavaScript and backend storage to complete the push notification system.