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:
Add the web-push gem to your project by running: bundle add web-push
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.
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.