Hi Rohit
Welcome to the Microsoft Q&A Platform!
setting up push notifications in your React web application with a Node Express backend using Azure Notification Hubs.
Use Azure Notification Hubs for push notifications.
Generate VAPID
keys using the web-push
library.
Go to Azure Portal >Create a Notification Hub >Set up a Namespace.
Generate VAPID keys
npx web-push generate-vapid-keys
Add VAPID public/private keys to Notification Hub settings under Push Notifications.
Set Up Service Worker (sw.js
).
self.addEventListener('push', (event) => {
const data = event.data.json();
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
});
});
Request Notification Permissions:
async function subscribeUser() {
const registration = await navigator.serviceWorker.register('/sw.js');
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: '<Your VAPID Public Key>',
});
await fetch('/api/save-subscription', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription),
});
}
Replace <Your VAPID Public Key>
with the public key from Azure Notification Hubs.
npm install web-push body-parser
Save and Send Notifications.
const express = require('express');
const webPush = require('web-push');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const publicVapidKey = '<Your VAPID Public Key>';
const privateVapidKey = '<Your VAPID Private Key>';
webPush.setVapidDetails('mailto:you@example.com', publicVapidKey, privateVapidKey);
let subscriptions = [];
app.post('/api/save-subscription', (req, res) => {
subscriptions.push(req.body);
res.status(201).json({});
});
app.post('/api/send-notification', (req, res) => {
const payload = JSON.stringify({ title: 'Hello!', body: 'This is a notification.' });
subscriptions.forEach((sub) =>
webPush.sendNotification(sub, payload).catch(console.error)
);
res.status(200).json({ message: 'Notifications sent' });
});
app.listen(3001, () => console.log('Server running on port 3001'));
https://zcusa.951200.xyz/en-us/azure/notification-hubs/
https://developer.mozilla.org/en-US/docs/Web/API/Push_API
If the answer is helpful, please click ACCEPT ANSWER and kindly upvote it .