π Send Web Push Notifications
NotificationAPI enables sending Web push notifications that display native-like notifications through your website, even when users arenβt on your site. Setup requires frontend integration (SDK + service worker), user permission, and backend sending. Hereβs how.
1. Setup Web Push in Your App (Frontend)
Web push notifications require frontend integration (SDK + service worker) and user permission before you can send notifications from your backend.
Install the Frontend SDK:
npm install @notificationapi/react Integrate the SDK by wrapping your app with NotificationAPIProvider:
import { NotificationAPIProvider } from '@notificationapi/react';
<App>
<NotificationAPIProvider
clientId="YOUR_CLIENT_ID"
userId="USER_ID"
customServiceWorkerPath="/notificationapi-service-worker.js"
>
{/* Your app content */}
</NotificationAPIProvider>
</App>; Set Up the Service Worker
The service worker is essential for receiving push notifications.
- Download notificationapi-service-worker.js
- Place the file in your
publicfolder. It should be accessible athttps://yourdomain.com/notificationapi-service-worker.js.
If the service worker is at a different path, specify it using the
customServiceWorkerPath parameter in the SDK initialization.
Request User Permission
You need to get the userβs permission to send web push notifications. You can do this programmatically:
const AskForPermission: React.FC = () => {
const notificationapi = NotificationAPIProvider.useNotificationAPIContext();
return (
<button
onClick={() => {
notificationapi.setWebPushOptIn(true);
}}
>
Enable Notifications
</button>
);
}; 2. Send Web Push Notifications from Your Backend
Now, send web push notifications from your backend:
Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the values from the
code sample in your NotificationAPI dashboard. These values can also be found
in the Environments section of the dashboard. The userId must match the userId
used in the frontend SDK.
import notificationapi from 'notificationapi-node-server-sdk';
// Initialize
notificationapi.init('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
// Send web push notification
notificationapi.send({
type: 'new_message',
to: {
id: 'USER_ID' // Must match userId in frontend SDK
},
webpush: {
title: 'New Message',
body: 'You have a new message!'
}
});
Youβre All Set!
π Congrats! Youβre now sending web push notifications!
For more advanced features like supported browsers, troubleshooting, and system notification settings, check out our Web Push Channel documentation.