DEV Community

Cover image for How to add web push notifications to your Next.js project with One Signal
Jerónimo Cosío
Jerónimo Cosío

Posted on

How to add web push notifications to your Next.js project with One Signal

I'm sure that by now you've seen the web push notifications that you get in certain websites, but maybe you aren't sure how to add them to your own. They're called web push notifications and they can help you to share relevant information to your users, or updates they're interested in even after they have left your site.

Example of web push notifications

To understand better on the browser side, this push notifications are part of the Notification Web APIs, I would suggest to dive deep into the API if you want to know more details about it. But today I want to show you how to use One Signal in your Next.js project to quickly start sending web push notifications with very few lines of code, in just a couple of minutes and for free!

I won't get into the details of setting up, running and deploying a Next.js project, so I'll assume that you already have a working Next.js site. If you don't have your Next.js project running I would suggest to start there first, please check out this amazing tutorial on the official docs. (For the deployment I'll be using Vercel, but you can use any other service.)

We'll be creating a website called Woof, which is inspired by a 'startup' created in The Office. This site will send a message to all of the users that subscribed and accepted to receive notifications through their browser, so every time any user sends a message through the UI, all the subscribers will get it. I know it's not the best use case, but I think it's easy enough for everyone to understand how to use push notifications and One Signal's SDK. You can also see the finished code for this post on my Github.

But enough chit chat lets dive right in, first we need to create a new account in One Signal and validate our email. After that we need to specify the name and the platform that we'll be sending push notifications to, for this example we'll be using 'Web'.
One Signal set up

On the setup we'll choose 'Typical Site' as we want to implement it fast and we're using Next.js which allows us to add our own JavaScript, on the second step it's really important to add the specific site url where the push notifications are going to be sent to, if you're still not sure which one to use, or you don't have a URL you can add localhost or similar, and son't worry, this can be edited later.

If you want, add an icon to be used on the notifications. On the third step you can edit the prompt message that your users will see to be subscribed to your notifications. Optionally you can create a welcome message and set up some advanced setting on step 4 & 5, but I'll skip that for now.

One Signal web configuration panel

One Signal permission prompt editor

After configuring the first steps, we'll get to a screen where we can download the One Signal SDK files, it's important to download them, unzip them and copy/transfer the OneSignalSDKUpdaterWorker.js and OneSignalSDKWorker.js files into the publicdirectory of your Next.js project.

On that screen we're going to find some JavaScript code to add to our site, BUT as we're using Next.js/React we need to set it up a little different and the relevant information for us there is the App ID.

To add the One Signal JavaScript SDK to our site we need to edit the <Head></Head> component on each page where we want to use it:

//...project-name/pages/index.js
<Head>
    <title>Title of the website here</title>
    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" 
async="">
    </script>
</Head>
Enter fullscreen mode Exit fullscreen mode

Then we want to initiate One Signal after the website has been loaded, to do that we'll use the useEffect hook from react like so :

//...project-name/pages/index.js
import Head from "next/head";
import React, { useEffect, useState } from "react";

export default function Home() {
  const [resultApi, setResultApi] = useState();
  useEffect(() => {
    window.OneSignal = window.OneSignal || [];
    OneSignal.push(function () {
      OneSignal.init({
        appId: "ONE-SIGNAL-APP-ID",
        notifyButton: {
          enable: true,
        },

        allowLocalhostAsSecureOrigin: true,
      });
    });
    return () => {
      window.OneSignal = undefined;
    };
  }, []);

//...
Enter fullscreen mode Exit fullscreen mode

Notice that you need to edit the appId: "ONE-SIGNAL-APP-ID",line with your own App ID.

And with that we're basically done with the implementation. After adding this code to our page component, you should be able to visit the Site URL specified in the configuration, and the notification prompt should appear for you to give permission and receive push notifications. You can look at a red bell in the lower right part of the site to debug the notifications.

Subscription button for Woof

Once a user subscribes and accepts to receive notifications they'll start appearing on your One Signal dashboard.

One Signal message audience

As a final step let's send our first notification, we'll create it through the One Signal dashboard by clicking on Messages on the top nav bar, and then the '+ New Push' button on the dashboard.

As you can see, you can add all the relevant information for the push notification like: audience, title, body, image, URL to launch when clicked, etc... and if needed, you can schedule the notification to be sent at a specific time. After you send it your subscribed, users should receive the notification directly in their browser/OS notifications.
Creating a notification from the manager on One Signal
Example pushed notification received

And that's it! In just a couple of minutes and with minimum set-up and lines of code we can start sending notifications to all of our users to share relevant information for them.

Thank you for reading, if this post gets enough traffic/attention, I'll create a second part to show how to use the One signal REST API to start sending notifications directly from our server instead of having to get into the One Signal interface to send each one of them, so if you enjoyed this post, please react to it, or comment if it's something that you may be interested in :).

Discussion (0)