🌐 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)

WARNING

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.

  1. Download notificationapi-service-worker.js
  2. Place the file in your public folder. It should be accessible at https://yourdomain.com/notificationapi-service-worker.js.
INFO

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:

TIP

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.