- Published on
Push notification in react and next js app using node js
- Authors
- Name
- Ganesh Negi
With that in mind, let's explore how to implement push notifications in a React and Next.js app using Node.js.

How Do Push Notifications Work in Web Apps?
Web push notifications operate through a combination of browser APIs, service workers, and a backend server that delivers messages to users.
When a user subscribes, the browser assigns a unique endpoint that the server can use to send push messages. If the browser is offline, notifications are queued and delivered once the user reconnects. These notifications function seamlessly across both desktop and mobile browsers, which is why they are also known as browser notifications.
What is a Service Worker?
A service worker is a background script that runs independently of a web page, enabling powerful features such as push notifications, background synchronization, and caching.
In the context of push notifications, the service worker acts as a bridge between the server and the client, receiving incoming push messages and displaying them to the user, even when the app is not open.
Registering a Service Worker
To register a service worker in a Next.js or React app, create a file named sw.js inside the public folder and implement the push event listener:
Example: public/sw.js
self.addEventListener("push", (event) => {
const data = event.data.json();
const notificationOptions = {
body: data.body,
icon: data.icon,
tag: "unique-tag", // Prevent duplicate notifications
data: { url: data.data.url }, // Redirect users when they click the notification
};
self.registration.showNotification(data.title, notificationOptions);
});
Here, the push event is triggered when the server sends a notification to the client. The service worker then processes the message and displays it to the user.
Registering a Service Worker in React and Next.js
To enable push notifications, we need to register the service worker in our React or Next.js app. This is done using the useEffect hook, which ensures the registration runs when the component mounts.
Implementation:
For Next.js (app/page.js) or React (src/index.js):
import { useEffect } from "react";
useEffect(() => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js")
.then(() => console.log("Service Worker registered successfully"))
.catch(() => console.log("Service Worker registration failed"));
}
}, []);
How It Works:
We check if the serviceWorker is available in the navigator object.
If supported, we register the service worker located at /sw.js.
If the registration is successful, we log a success message; otherwise, we log an error.
This ensures that the service worker is properly registered, allowing the app to handle push notifications in the background.
Sending Push Notifications from the Server
To send push notifications from a Node.js server, we use the web-push library. This requires generating a VAPID key pair and configuring our backend to handle subscriptions and notifications.
Step 1: Install web-push
Run the following command to install web-push:
npm install web-push -g
Generate a VAPID key pair:
web-push generate-vapid-keys
This will generate a public key and private key, which should be stored in environment variables.
Step 2: Setup the Node.js Server
Example: server.js
import express from "express";
import webpush from "web-push";
import dotenv from "dotenv";
dotenv.config();
const app = express();
app.use(express.json()); // Middleware to parse JSON requests
const vapidKeys = {
publicKey: process.env.VAPID_PUBLIC_KEY,
privateKey: process.env.VAPID_PRIVATE_KEY,
};
// Configure web-push with VAPID details
webpush.setVapidDetails(
"mailto:test@gmail.com", // Replace with your email
vapidKeys.publicKey,
vapidKeys.privateKey
);
let subscriptions = []; // Store subscriptions (ideally, use a database)
// **Route to handle subscriptions**
app.post("/subscribe", (req, res) => {
const subscription = req.body;
subscriptions.push(subscription);
res.status(201).json({ status: "Subscribed successfully" });
});
// **Route to send push notifications**
app.post("/send-notification", (req, res) => {
const notificationPayload = {
title: "New Notification",
body: "You have a new message!",
icon: "https://some-image-url.jpg",
data: { url: "https://example.com" },
};
Promise.all(
subscriptions.map((subscription) =>
webpush.sendNotification(subscription, JSON.stringify(notificationPayload))
)
)
.then(() => res.status(200).json({ message: "Notification sent successfully." }))
.catch((err) => {
console.error("Error sending notification:", err);
res.sendStatus(500);
});
});
app.listen(4000, () => {
console.log("Server running on port 4000");
});
How It Works
Subscription Handling (/subscribe)
When a user subscribes to push notifications, their subscription object is stored in an array (or a database).
Sending Notifications (/send-notification)
The server loops through all subscriptions and sends push notifications using webpush.sendNotification().
We use Promise.all() to send notifications to multiple users at once.
You can filter the subscriptions array to send notifications to specific user
Storing Subscriptions
Instead of keeping subscriptions in memory, store them in a database (e.g., MongoDB, PostgreSQL). This ensures that notifications persist across server restarts.
Subscribing to Push Notifications in React and Next.js
To receive push notifications, we need to subscribe the client to push notifications using the service worker. This is done via the pushManager.subscribe() method.
Implementation:
For Next.js (app/page.js) or React (src/index.js):
import { useEffect } from "react";
const VAPID_PUBLIC_KEY = "YOUR_VAPID_PUBLIC_KEY"; // Replace with your actual VAPID public key
useEffect(() => {
if ("serviceWorker" in navigator) {
const handleServiceWorker = async () => {
try {
// Register the service worker
const register = await navigator.serviceWorker.register("/sw.js");
// Subscribe to push notifications
const subscription = await register.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: VAPID_PUBLIC_KEY,
});
// Send the subscription object to the server
const res = await fetch("http://localhost:4000/subscribe", {
method: "POST",
body: JSON.stringify(subscription),
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
console.log("Subscription successful:", data);
} catch (error) {
console.error("Push subscription failed:", error);
}
};
handleServiceWorker();
}
}, []);
How It Works:
Register the Service Worker
The navigator.serviceWorker.register("/sw.js") method registers the service worker, enabling background notifications.
Subscribe to Push Notifications
The pushManager.subscribe() method creates a subscription object containing the user's push notification preferences.
We pass the VAPID_PUBLIC_KEY to verify our server when sending notifications.
Send Subscription to the Server
The subscription object is sent to the /subscribe endpoint of our Node.js server, allowing it to store and use the subscription for sending push notifications.
Next Steps: Replace "YOUR_VAPID_PUBLIC_KEY" with the actual public key generated using web-push generate-vapid-keys.
Ensure the server is running (node server.js) before testing the subscription.
Now, your React/Next.js app is subscribed to push notifications, and the server can send messages to subscribed users! 🚀
Sending Push Notifications from the Server
Once your server is running, you can manually trigger a push notification using Postman or any API testing tool.
Step 1: Start the Server
Run the following command in your terminal:
node server.js
This will start your Express.js server on port 3009.
Step 2: Send a Push Notification Using Postman
Open Postman
Select POST as the request method.
Enter the following URL:
http://localhost:3009/send-notification
Click Send
Once the request is sent, all subscribed users will receive the push notification in their browser!
Conclusion
In this article, we explored how to implement push notifications in a React and Next.js app using Node.js.
We covered:
✅ Setting up a service worker to handle push notifications.
✅ Registering the service worker in a React/Next.js app.
✅ Subscribing users to push notifications.
✅ Using web-push in a Node.js server to send notifications.
✅ Sending push notifications using Postman.
This implementation provides a basic push notification system. You can extend it further by:
🔹 Sending notifications to specific users or user groups.
🔹 Storing subscriptions in a database for better management.
🔹 Integrating custom notification messages and actions.
Now, your app is ready to engage users with real-time push notifications! 🚀