DEV Community

Cover image for Web Push Notifications with React and Pushpad
Marco Colli
Marco Colli

Posted on

2

Web Push Notifications with React and Pushpad

In this tutorial we'll see how to easily subscribe a user to web push notifications on a React website.

In particular we build a React component: a button that allows a user to subscribe / unsubscribe from push notifications.

We'll use the Pushpad SDK to create and manage the push subscription.

Setup the Pushpad JavaScript SDK

First you need to add a file named service-worker.js to the root folder of your website. Then add this line of code to that file:

importScripts('https://pushpad.xyz/service-worker.js');
Enter fullscreen mode Exit fullscreen mode

Then copy and paste this code to your website:

<script>
  (function(p,u,s,h,x){p.pushpad=p.pushpad||function(){(p.pushpad.q=p.pushpad.q||[]).push(arguments)};h=u.getElementsByTagName('head')[0];x=u.createElement('script');x.async=1;x.src=s;h.appendChild(x);})(window,document,'https://pushpad.xyz/pushpad.js');

  pushpad('init', PROJECT_ID);
</script>
Enter fullscreen mode Exit fullscreen mode

Replace PROJECT_ID with your project ID (you can find it in the project settings in the Pushpad dashboard).

Note: Pushpad init will also try to register the service-worker.js file. If your app already has a service worker and you register it from your custom code, you can skip that by calling pushpad('init', PROJECT_ID, { serviceWorkerPath: null });.

The JavaScript SDK functions

Now the fun part. You can build any UI component (like a subscribe button for push notifications, a custom modal for push notifications, etc.) with your custom style and a few simple methods:

  • you can subscribe the user to your notifications and display the native permission prompt for push notifications using pushpad('subscribe')
  • you can get the current push subscription status with pushpad('status')
  • you can unsubscribe the user from push notifications using pushpad('unsubscribe')
  • you can also authenticate your users with pushpad('uid') or attach other data for targeting with pushpad('tags').

The React component: a button for web push notifications

This is the React code for building a subscribe / unsubscribe button for web push notifications:

const PushSubscriptionButton = () => {
  const [subscribed, setSubscribed] = useState(null);

  useEffect(() => {
    pushpad('status', (isSubscribed) => {
      setSubscribed(isSubscribed);
    });
  }, []);

  const subscribe = () => {
    pushpad('subscribe', (isSubscribed) => {
      if (isSubscribed) {
        setSubscribed(true);
      } else {
        alert('Notifications are blocked from browser preferences.');
      }
    });
  };

  const unsubscribe = () => {
    pushpad('unsubscribe', () => {
      setSubscribed(false);
    });
  };

  if (subscribed == null) {
    return null;
  }

  return subscribed ? (
    <button onClick={unsubscribe} style={{ color: 'white', background: 'gray' }}>
      Subscribed
    </button>
  ) : (
    <button onClick={subscribe} style={{ color: 'white', background: 'red' }}>
      Subscribe
    </button>
  );
};
Enter fullscreen mode Exit fullscreen mode

The code is self-explanatory.

First it detects if the user is subscribed or not to the push notifications. If the user is not subscribed it display a "Subscribe" button, otherwise, if the user is already subscribed, it displays the text "Subscribed".

When a user clicks the "Subscribe" button, they will see the browser permission prompt for push notifications: if they accept, they will be subscribed to your website notifications.

The button will also display the current status (e.g. "Subscribed") and if you click on it again you can also unsubscribe from push notifications.

Sending the notifications

Now that you have the subscribers you can send some push notifications. The push notifications are delivered and displayed even when the users are not on your website. For example, if you have a blog, you may want to send a notifications when there is a new post; if you own an e-commerce you can promote the products, etc.

The easiest way to send the notifications is to use the Pushpad dashboard to send the notifications manually.

Otherwise you can also send the notifications from your server-side code using the API (Pushpad has some official libraries for Node.js and for other popular languages).

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay