Real-Time Engagement: Web Push Notifications in Rails 8

Solo developers often face a wall when building mobile features. You used to need a native app to send push notifications. If you did not have one, you relied on email or expensive SMS.

The Web Push API changes this. It works on almost every browser, including Safari on iOS. You can send alerts directly from your Rails app to a user's device. They do not need to download anything from an App Store.

Here is how you set it up in Rails 8.

The Workflow

  • Subscription: The user clicks allow in their browser. The browser provides a subscription object.
  • Storage: You save this object in your database tied to the user.
  • The Push: Your Rails server sends a signed message to the browser push service.
  • Delivery: The service worker on the device shows the notification.

Setup Steps

  1. Security You need VAPID keys to identify your server. This prevents hackers from sending fake alerts. Add the web-push gem to your Gemfile. Run web-push generate-vapid-keys in your terminal. Save these keys in your credentials file.

  2. Database Users often have multiple devices. Create a model to store subscriptions. Run: rails g model WebPushSubscription user:references endpoint:string p256dh_key:string auth_key:string Run: rails db:migrate

  3. Service Worker Create public/service-worker.js. This file runs even when your website is closed. It listens for the push event and shows the notification.

  4. Frontend Register the worker in your application.js. Use a Stimulus controller to ask for permission. Send the subscription data to your Rails controller via a POST request.

  5. Background Jobs Never send notifications in the main request cycle. Use a background job to avoid slowing down your app. Create a SendWebPushJob. Loop through a user's subscriptions. Use the web-push gem to send the payload. Delete subscriptions if they are no longer valid.

You can build an app that feels like a native mobile experience using only Rails and small amounts of Javascript.

Source: https://dev.to/zilton7/real-time-engagement-web-push-notifications-in-rails-8-5gdp