DEV Community

Cover image for Push Notifications in ReactJS with OneSignal
Pato
Pato

Posted on • Edited on

Push Notifications in ReactJS with OneSignal

In this tutorial, you are going to learn how to communicate with the users of your application by integrating push notifications and subscriptions into your ReactJS application using OneSignal.

Topics covered in this tutorial

  • ReactJS
  • Push Notifications
  • OneSignal Segments
  • Audience
  • Subscriptions
  • One Signal's SDK

Before we begin, it's important to define what a push notification is.

What is a Push Notification?

Push notifications are clickable pop-up messages that appear on your usersโ€™ browsers irrespective of which device they use or which browser they are on. Subscribers can be anywhere on the browser and still receive these messages even if the website or app are not running.

Browser push notifications are different from in-app notifications because in-app notifications appear only when triggered by an existing application on your mobile device; browser push notifications can be triggered through browsers on any device as long as the user subscribes to receive your notifications. It is an instant mode of automated, direct communication between a website and its end users.

Time to get our hands dirty!!! ๐ŸŽŠ

In this tutorial, we are going to use OneSignal to send the push notifications and handle the subscriptions.

OneSignal is the market leader in customer engagement, powering mobile + web push, email, SMS & in-app messages.

The first thing that we have to do is to create an account inside of OneSignal

1) Once you have created an account, you will create a new application

OneSignal React

2) When creating the app, you can give it whatever name you want. Make sure sure the "No Organization" option is selected from the organizations dropdown. Lastly, click on Web Push and click NEXT.

OneSignal React

3) Configure your Web Push by entering the website's name and by entering the site's URL then click SAVE.

Notes

-Keep in mind that your application has to be hosted in a server for the Push Notifications to work. If you want to deploy your website in a quick and easy way, follow this 2min tutorial.

-You can enter a default URL icon but this is an option, not mandatory.

OneSignal

4) Download the SDK files and save them in a place you will remember in your computer because we are going to use them later on.

The .zip file you are downloading contains 2 files. These are the Service Workers provided by OneSignal. To learn more about Service Workers in general read this article.

DO NOT CLOSE THE CONFIG PAGE. WE WILL BE BACK TO IT SOON.

Integrating OneSignal To Your ReactJS App

Feel free to clone the repo with the basic structure of the React application where we will integrate OneSignal or follow the steps given in this tutorial to integrate OneSignal into your own React application.

Github repo

https://github.com/devpato/onesignal-demo

-initial state branch (INIT)
-final code branch (MAIN)

5) Inside of the React project, the first thing you are going to do is to add the services worker files you downloaded into your PUBLIC folder.

You should be adding 2 files:

  • OneSignalSDKUpdaterWorker.js
  • OneSignalSDKWorker.js

OneSignal React

6) In the same folder (PUBLIC) you have a file called Index.html. Go to that file and paste the following line of code inside of you <head></head> tag.



<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>


Enter fullscreen mode Exit fullscreen mode

Your file should look something like this:



<head>
.
.
.
  <title>One Signal - React</title>
  <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
</head>


Enter fullscreen mode Exit fullscreen mode

7) Open the App.js file located inside of the SRC folder and paste the code



  window.OneSignal = window.OneSignal || [];
  const OneSignal = window.OneSignal;


Enter fullscreen mode Exit fullscreen mode

This code will allows us to have access to the OneSignal object that we injected into our app thanks to the SDK we added in the index.html file.

8) In the same file, inside of the useEffect add the following code:



OneSignal.push(()=> {
      OneSignal.init(
        {
          appId: "1a9bbed2-9294-4192-a736-01b461cb389a", //STEP 9
          promptOptions: {
            slidedown: {
              enabled: true,
              actionMessage: "We'd like to show you notifications for the latest news and updates about the following categories.",
              acceptButtonText: "OMG YEEEEESS!",
              cancelButtonText: "NAHHH",
              categories: {
                  tags: [
                      {
                          tag: "react",
                          label: "ReactJS",
                      },
                      {
                        tag: "angular",
                        label: "Angular",
                      },
                      {
                        tag: "vue",
                        label: "VueJS",
                      },
                      {
                        tag: "js",
                        label: "JavaScript",
                      }
                  ]
              }     
          } 
        },
        welcomeNotification: {
          "title": "One Signal",
          "message": "Thanks for subscribing!",
        } 
      },
        //Automatically subscribe to the new_app_version tag
        OneSignal.sendTag("new_app_version", "new_app_version", tagsSent => {
          // Callback called when tag has finished sending
          console.log('new_app_version TAG SENT', tagsSent);
        })
      );
    });


Enter fullscreen mode Exit fullscreen mode

Let's talk about the previous code. The OneSignal object can only be initialized once .init(). In this example we are triggering the initialization as soon as the App component loads.

The promptOptions property will hold all the information related to the prompt message we are displaying to the user.

slidedown property is the type prompt that will slide down from the top of your page. This type of prompt has multiple properties you can use to customize it. Let's take a look to some of those properties:

-actionMessage: This is the main message to display in the prompt.

-acceptButtonText: Text for the accept button inside of the prompt.

-cancelButtonText: Text for the cancel button inside of the prompt.

OneSignal React

categories: Property that takes an array of tags. The Category Slidedown works just like the regular Slide Prompt except it also allows subscribers to opt-in or opt-out of notification categories set as Data Tags.

Alt Text

welcomeNotification: Displays a in-app notification after we have clicked on the accept button inside of the prompt and after the user has allowed the notifications in the app and after.

Finally, at the bottom of the code provided above, you will see the following code:



OneSignal.sendTag("new_app_version", "new_app_version", tagsSent => {
   console.log('new_app_version TAG SENT', tagsSent);
})


Enter fullscreen mode Exit fullscreen mode

sendTags will send a tag to OneSignal specifying the tag the users belong too. We can use these tags to target users by creating segments for things like marketing campaigns. The cool thing about sendTag is that you can use this method in other parts of your app without the need of a prompt. For example you can use them on a click of a button.

9) Now, let's go back to the configuration page inside the OneSignal website. Once you are in there, you are going to copy the appId inside of the "Add code to site" section. Your app ID is unique per application. If you try to use mine, it won't work.

OneSignal

After you have copied the appId, go back to your App.js file inside of your ReactJS app and inside of the OneSignal object assign your copied appId to the appId property.

10) Now build you app and deploy it to your server.

YAY! we are done with the code part!

11) Navigate to your app's website. You should see the following:

OneSignal

-Click on Allow on the OneSignal prompt

After you have clicked allow on the OneSignal prompt we will see this browser message

OneSignal

Click "Allow" and you will see the in-app (welcomeNotification)

OneSignal React

The OneSignal Platform

12) Let's go back to the OneSignal website. We are going to create a new Segment to target specific users for our marketing campaign.

On the top navigation bar of the website, click where it says "audience". Once you are in that section, click the blue button that says "New Segment"

OneSignal

A modal as the following will appear

OneSignal

Enter whatever name you want for you Segment and click on "User tag".

OneSignal React

Create the user segments rules. Once you are done, click on the blue button "Create Segment".

YAY! you have officially created you first Segment.

Time to test our application!

13) We are going to create our first Push Notification using OneSignal. Navigate to Messages and click on the blue button "New Push".

OneSignal React

In the "Audience" section select "Send to Particular Segment(s)". Remove the segment of "Subscribed Users" and add the Segment you just created.

OneSignal React

For the "Message" section enter the title, message, and icon you want the Push notification to have.

OneSignal React

Lastly, in the "Schedule" section select "Begin sending immediately" and "Send immediately" and click on the blue button "Confirm"

OneSignal React

Review your message before sending and click "Send message" and see the magic happening :)

OneSignal React

You will receive see your first Push notification coming from OneSignal!

OneSignal

Conclusion

OneSignal is a great tool to interact with the application's users. OneSignal is a great communication tool. This tool allows you not only to send Push notifications but also to target specific segments of users you want to interact with. OneSignal has a great Dashboard where you can keep track of how your users are interacting with your Push notifications or any other tool inside of OneSignal used to communicate with the users like SMS, emails, and more. I have used other technologies to send Push notifications and from my point of view, OneSignal was the one that was the easiest to integrate into your website. You can integrate it to a regular HTML/CSS/JS website with almost no programming experience.

Resources

https://vwo.com/push-notifications/
https://documentation.onesignal.com/docs

Top comments (28)

Collapse
 
kannant14 profile image
Kannan T

[Worker Messenger] [Page -> SW] Could not get ServiceWorkerRegistration to postMessage!

Am facing this error any idea why?

Collapse
 
nostin profile image
Sean Thompson

I'm getting this intermittently too.

Collapse
 
kannant14 profile image
Kannan T

@sean Thompson

This issue occurs when you are not subscribed to onesignal, i figured this out yesterday while working @pato you can make a note of this, if some one reported to you regarding this ask them whether they have subscribed or not

Thread Thread
 
devpato profile image
Pato

Awesome! Thanks so much

Thread Thread
 
comorina profile image
Shivam Pandey • Edited

Hey Pato, I am still facing this issue can you give some suggestion that can help me. (User has subscribed already)
Thank you

Collapse
 
kannant14 profile image
Kannan T

check your configuration mostly that should be the problem

Thread Thread
 
devpato profile image
Pato

Did you get it fixed Kannan? Is there something I need to fix from the article?

Thread Thread
 
kannant14 profile image
Kannan T

No pato, your article is fine and it helped me allot, thank you for the article

Collapse
 
kannant14 profile image
Kannan T

Thanks for the article, but how do i test this out in local environment? Is there any way we can do it, because everytime i do some changes i can't push it to production and test it

Collapse
 
kannant14 profile image
Kannan T

And also am facing an issue here, i will post that tomorrow morning as its late night here, your article helped me to start up with one signal thank you

Collapse
 
devpato profile image
Pato • Edited

Hi I need to update the docs but essentially you will do this as the image shown, that way you dont have to keep redeploying our app all the time

dev-to-uploads.s3.amazonaws.com/up...

Thread Thread
 
kannant14 profile image
Kannan T • Edited

Hi i can't see local testing button from my side attaching screenshot as reference

dev-to-uploads.s3.amazonaws.com/up...

Thread Thread
 
devpato profile image
Pato

You have to enter a localhost url that way the form will detect it and give you the options you need

Thread Thread
 
kannant14 profile image
Kannan T

Thanks it worked with localhost now, now ill show the issue am facing

dev-to-uploads.s3.amazonaws.com/up...

Thread Thread
 
devpato profile image
Pato

Did you download and add the sdk files into your project?

5) Inside of the React project, the first thing you are going to do is to add the services worker files you downloaded into your PUBLIC folder.

You should be adding 2 files:

OneSignalSDKUpdaterWorker.js
OneSignalSDKWorker.js

You can download the files here too github.com/OneSignal/OneSignal-Web...

Collapse
 
sathittham profile image
sathittham

Thank you for sharing this. I wonder how can I listen to OneSignal Event with ReactJS (and do something else with that data) after I received the notification.

Collapse
 
devpato profile image
Pato

Hi Sathittham! I want to make sure I'm understanding the question.

1) I send a push notification from the OneSignal portal
2) I received a push notification that has the title and body Ex.

React JS tutorial
Take a look to my new ReactJS tutorial!!

and then in your ReactJS app grab the title of the push notification?

Collapse
 
sathittham profile image
sathittham

Yes, I want to grab data (id, heading, content, data, url, icon) from the notification.

Thread Thread
 
sajideen profile image
Sajideen

Hi @sathittham, I am looking for the same thing. If you have done it, please share the event that was triggered to achieve this.

Collapse
 
ibengeu profile image
ibenge Uforo

Hey, thanks for this article. it was really helpful but ran into a problem.

How can we use this with a PWA having it's own service worker?

Collapse
 
devpato profile image
Pato

You can, you will have to change the scope of the service worker of OneSignal.-

something like this:

OneSignal.SERVICE_WORKER_PARAM = { scope: '/assets/js/' };
OneSignal.SERVICE_WORKER_PATH = '../assets/js/OneSignalSDKWorker.js';
OneSignal.SERVICE_WORKER_UPDATER_PATH = '../assets/js/OneSignalSDKUpdaterWorker.js';
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ibengeu profile image
ibenge Uforo

I'm back again Pato, been on this for weeks.

At the moment, i'm getting "the script resource is behind a redirect which is disallowed" and have tried

  • switching positions of the folder from src to root ie. where React service worker files and it's registration is.
  • Placing the main files without the folder at the root.
  • changing scope url to an absolute path but to no avail.
  • Registering the oneSignal service worker file in place of reacts and using the importScript.

Please help.

Collapse
 
nostin profile image
Sean Thompson

Hi Pato, thank you for this it is working really well but I don't understand this part. In mine the scope is set to /push/onesignal/... what is this doing?

Thread Thread
 
devpato profile image
Pato

Can you show me a screenshot of where you are seeing that, please? Thank you so much!

Collapse
 
jelugom profile image
J. Elias Lugo

Hi, I have a problem, maybe my implementation is wrong, but I want your feedback, I've tried to implement onesignal on my reactjs web app (it's not react native).

I tried 3 differents aproachs:
1.- Following the oficial onesignal web push sdk documentation.
2.- This aproach.
3.- Using this package github.com/pedro-lb/react-onesigna...

All of them I've completed successfully, but all have a strange behavior on my reactjs web app.

When my app get the notifications permissions for first time and I accept it, it doesn't show the welcome notification and if I send a notification from my onesignal dashboard it doesn't show.

If I refresh (F5) my app two times and send another notification, it works and show correctly. But if for any reason I refresh again my app, the notifications don't work anymore and in my onesignal dashboard shows that my player id is unsubscribe.

Somebody has the same issue? or what could be wrong in my app? Thanks.

Collapse
 
devpato profile image
Pato

Hi Elias! Interesting problem. I haven't run into that issue. If you can create a minimal replication of you project and paste the link to your repo here I can try it on my computer.

what browser are you using?

Collapse
 
danishalikhan688 profile image
danishalikhan688

window.OneSignal = window.OneSignal || [];
Showing error in app.tsx

Collapse
 
pcast01 profile image
Paul

I used this code from: stackoverflow.com/questions/564579...

declare global {
interface Window {
OneSignal: any;
}
}