Enable Dark Mode!
how-to-implement-push-notifications-in-a-react-pwa.jpg
By: Alan Joy

How to Implement Push Notifications in a React PWA

Technical

Progressive Web Apps (PWAs) have become a powerful way to deliver fast, engaging, and reliable web experiences. One of the key features that enhances user engagement in a PWA is push notifications. These alerts help you keep your users updated, even when your app is not open in their browser.

In this blog, we’ll walk through the steps to implement push notifications in a React-based PWA. Whether you're building a task manager, an e-commerce store, or a news app, push notifications can play a vital role in user engagement.

What are Push Notifications?

Push notifications are messages sent from a server to a user's device. They're delivered outside the app’s interface, like banners, alerts, or pop-ups. In web apps, these are handled via the Push API and Service Workers.

To implement push notifications, you'll need:

  • A Service Worker to handle background tasks.
  • A Push Notification Server to send messages.
  • A UI for user permission and subscribing to notifications.

Step 1: Set Up Your React App

First things first, let’s create a React app.

Open your terminal and run:

npx create-react-app my-pwa-app
cd my-pwa-app
npm start

Once the development server starts, your app will be running at http://localhost:3000.

Step 2: Add the Web App Manifest

The manifest file tells the browser this is a PWA and gives it details like the name, icon, and theme color.

Create a file named manifest.json in the /public folder with the following content:

{
  "short_name": "MyPWA",
  "name": "My React PWA",
  "start_url": ".",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#317EFB",
  "icons": [
    {
      "src": "logo192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "logo512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

Then, add this to your public/index.html inside the tag:

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

Step 3: Create and Register a Service Worker

To receive push notifications, your app must have a registered service worker.

Create a new file: public/service-worker.js

self.addEventListener('push', event => {
  const data = event.data.json();
  const options = {
    body: data.body,
    icon: '/logo192.png',
  };
  event.waitUntil(
    self.registration.showNotification(data.title, options)
  );
});

Now, register this service worker in your React app. Open src/index.js and add this at the bottom:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker
      .register('/service-worker.js')
      .then(registration => {
        console.log('Service Worker registered:', registration);
      })
      .catch(error => {
        console.error('Service Worker registration failed:', error);
      });
  });
}

This step ensures your app runs in the background and can handle incoming push notifications, even when closed.

Step 4: Set Up Push Notifications with a Custom Hook

Now that your service worker is registered, let's set up push notifications in a clean and reusable way.

We’ll create a custom React Hook that:

  • Asks the user for notification permission
  • Subscribes the user to push notifications
  • Sends the subscription details to your backend

1. Create a file usePushNotifications.js

import { useEffect } from 'react';
export function usePushNotifications() {
  useEffect(() => {
    const setupPush = async () => {
      if (!('Notification' in window) || !('serviceWorker' in navigator)) return;
      // Ask for permission
      const permission = await Notification.requestPermission();
      if (permission !== 'granted') {
        console.log('Notification permission not granted');
        return;
      }
      // Wait for service worker to be ready
      const registration = await navigator.serviceWorker.ready;
      // Check if already subscribed
      const existing = await registration.pushManager.getSubscription();
      if (existing) {
        console.log('Already subscribed to push');
        return;
      }
      // Subscribe the user
      const subscription = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: '<YOUR_VAPID_PUBLIC_KEY>',
      });
      console.log('Push subscription:', subscription);
      // Send to your backend
      await fetch('http://localhost:4000/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(subscription),
      });
    };
    setupPush();
  }, []);
}

Note: You’ll generate your VAPID_PUBLIC_KEY in the next step.

2. Use the Hook in App.js

import React from 'react';
import { usePushNotifications } from './usePushNotifications';
function App() {
  usePushNotifications();
  return (
    <div className="App">
      <h1>Welcome to Your React PWA</h1>
    </div>
  );
}
export default App;

Step 5: Set Up a Backend to Send Push Notifications

To actually send a push notification, you need a server that can talk to the Web Push API.

We’ll create a simple backend using Node.js + Express + web-push.

Setup Instructions

Create a new directory for the backend:

mkdir push-server
cd push-server
npm init -y
npm install express web-push body-parser cors

Generate VAPID keys:

npx web-push generate-vapid-keys

Copy the public key (for frontend) and private key (for backend).

Backend Code (index.js)

const express = require('express');
const webPush = require('web-push');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const publicVapidKey = '<YOUR_PUBLIC_KEY>';
const privateVapidKey = '<YOUR_PRIVATE_KEY>';
webPush.setVapidDetails(
  'mailto:your@email.com',
  publicVapidKey,
  privateVapidKey
);
let subscriptions = [];
app.post('/subscribe', (req, res) => {
  const subscription = req.body;
  subscriptions.push(subscription);
  res.status(201).json({ message: 'Subscribed successfully' });
});
app.post('/send', (req, res) => {
  const payload = JSON.stringify({
    title: 'Hey there!',
    body: 'This is your push notification ??',
  });
  subscriptions.forEach(sub => {
    webPush.sendNotification(sub, payload).catch(console.error);
  });
  res.status(200).json({ message: 'Notification sent' });
});
app.listen(4000, () => {
  console.log('Push server running on http://localhost:4000');
});

Start the backend:

node index.js

Now your backend is ready to receive subscriptions and send push messages.

Step 6: Triggering the Notification

Alright, the setup is done, your user has granted permission, subscribed, and your service worker is ready to receive push events.

Now, let’s trigger the actual push notification. Open your terminal and run:

curl -X POST http://localhost:4000/send

Push notifications are a fantastic way to add value to your PWA, whether you’re sending reminders, updates, or alerts. With React and a little bit of backend help, you now have a complete system from requesting permission to delivering notifications.

To read more about How to Build a Progressive Web App (PWA) with React, refer to our blog How to Build a Progressive Web App (PWA) with React.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message