How to add push notifications into a Next.js App
Tags: webdev, javascript, react, nextjs
Published: 2021-06-16 22:23:20

---
title: How to add push notifications into a Next.js App
published: true
date: 2021-06-16 19:53:12 UTC
tags: webdev,javascript,react,nextjs
canonical_url: 
---

 ![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/onesignal-nextapp-integration.png)

Web push notifications are a versatile channel that can be used to enhance your UX, re-engage users, promote new products or features, ignite engagement, drive revenue, and [increase user retention](https://onesignal.com/blog/easy-strategies-to-increase-app-retention/). Compared to traditional channels such as email, [web push notifications](https://onesignal.com/webpush) capture user's attention more quickly and can drive immediate engagement, which is ideal for time-sensitive content. The best part? You can add this powerful communication channel to your Next app for free.

In this guide, I'll show you how to integrate with OneSignal in order to add web push notifications to a React app built using the [Next.js](https://nextjs.org/) framework. This article is written with the assumption that you already know a little bit about Next.js — my focus will be on executing the OneSignal integration. In an effort to make this guide as useful to as many people as possible, I will start from scratch and cover the Next.js app setup process as well as the OneSignal integration and messaging process.

At the time this guide was written, I had the following dependencies installed on my system: **macOS 11.3.1** , [**Node v14.15.1**](https://github.com/nodejs/node/releases/tag/v14.15.1), [**Yarn 1.22.10**](https://github.com/yarnpkg/yarn/releases/tag/v1.22.10), [**Next.js v10.2.0**](https://github.com/vercel/next.js/releases/tag/v10.2.0) (latest at the time of writing). You should be able to follow along so long as you have **Node version 14 or later**.

### Guide Overview

- [Creating Your Next App](#creating-your-next-app)
- [Getting the OneSignal SDK](#getting-the-onesignal-sdk)
- [Adding the OneSignal SDK Script to Your App](#adding-the-onesignal-sdk-script-to-your-app)
- [Part 1: Initializing the OneSignal SDK](#part-1-initializing-the-onesignal-sdk) 
- [Configuring Your Next App in OneSignal](#configuring-your-next-app-in-onesignal)
- [Part 2: Initializing the OneSignal SDK](#part-2-initializing-the-onesignal-sdk)
- [Sending & Receiving Notifications](#sending-receiving-notifications)
- [Additional Support & Helpful Resources](#additional-support-helpful-resources)

If you don't yet have a OneSignal account, [create a free account](https://app.onesignal.com/signup) before you begin this guide. Don't worry about configuring your account just yet — simply create your login and password and I'll walk you through the platform setup and initialization process later on in this guide.

## Creating Your Next App

Execute `yarn create next-app`.

<!--kg-card-begin: code-->
```
╭─iamwillshepherd@ares ~/code/onesignal-nextjs ‹main›
╰─$ yarn create next-app .
yarn create v1.22.10
[1/4] 🔍 Resolving packages...
[2/4] 🚚 Fetching packages...
[3/4] 🔗 Linking dependencies...
[4/4] 🔨 Building fresh packages...

success Installed "create-next-app@10.2.0" with binaries:
      - create-next-app
[##] 2/2Creating a new Next.js app in /Users/iamwillshepherd/code/onesignal-nextjs.

Installing react, react-dom, and next using yarn...
```
<!--kg-card-end: code-->

When the command completes, you should see console output similar to this:

<!--kg-card-begin: code-->
```
Success! Created onesignal-nexgtjs at /Users/iamwillshepherd/code/onesignal-nextjs
Inside that directory, you can run several commands:

  yarn dev
    Starts the development server.

  yarn build
    Builds the app for production.

  yarn start
    Runs the built app in production mode.

We suggest that you begin by typing:

  cd /Users/iamwillshepherd/code/onesignal-nextjs
  yarn dev

✨ Done in 4.75s.
```
<!--kg-card-end: code-->

You can check out the excellent [Next documentation](https://nextjs.org/docs) to learn what this (☝🏾) command does.

Execute `yarn dev` to verify the app works as expected.

<!--kg-card-begin: code-->
```
╭─iamwillshepherd@ares ~/code/onesignal-nextjs ‹main*›
╰─$ yarn dev
yarn run v1.22.10
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Using webpack 5. Reason: no next.config.js https://nextjs.org/docs/messages/webpack5
event - compiled successfully
event - build page: /next/dist/pages/_error
wait - compiling...
event - compiled successfully
```
<!--kg-card-end: code-->

Navigate to the URL returned in the output with your browser of choice.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-17_at_12.23.19_PM.png)<figcaption>The expected result when navigating to URL in run output.</figcaption>

<!--kg-card-end: image-->
## Getting the OneSignal SDK

Our platform allows you to integrate with dozens of third parties. Because I'm integrating OneSignal into a React app, I must manually add the SDK service workers to the app. For instructions on how to do so, check out our [Custom Code Setup Documentation](https://documentation.onesignal.com/docs/web-push-custom-code-setup). To get started, download the OneSignal SDK archive [here](https://documentation.onesignal.com/docs/web-push-custom-code-setup#step-3-upload-onesignal-sdk).

Unzip the archive contents into your project into the `public` directory of your Next app. The OneSignal Web SDK directory contains service workers that do the heavy lifting of handling notifications. These service workers must be publicly accessible, so we use Next's [static file servicing](https://nextjs.org/docs/basic-features/static-file-serving) to achieve this.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-17_at_2.27.14_PM.png)

<!--kg-card-end: image-->

Ignore the contents of `public` and `__MACOSX`. Move all JavaScript files from `OneSignal-Web-SDK/` to `public/`.

<!--kg-card-begin: code-->
```
╭─iamwillshepherd@ares ~/code/onesignal-nextjs/public ‹main*›
╰─$ mv OneSignal-Web-SDK-HTTPS-Integration-Files/*.js .
```
<!--kg-card-end: code-->

Confirm that the files have been moved and then remove the highlighted files.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-17_at_3.44.51_PM.png)

<!--kg-card-end: image-->

Finally, cleanup the `public` directory.

<!--kg-card-begin: code-->
```
╭─iamwillshepherd@ares ~/code/onesignal-nextjs/public ‹main*›
╰─$ rm -rf __MACOSX OneSignal-Web-*
```
<!--kg-card-end: code-->
## Adding the OneSignal SDK Script to Your App

The OneSignal SDK script must be loaded to make use of the two service workers. Add the OneSignalSDK script under the `Head` component in `pages/index.js`.

Add the following script tag

<!--kg-card-begin: code-->
```html
<head>
  <title>OneSignal + Next.js</title>
  <meta
    name="description"
    content="Integrating OneSignal with a Next.js app."
  />
  <link rel="icon" href="/favicon.ico" />
  <script
    src="https://cdn.onesignal.com/sdks/OneSignalSDK.js"
    async=""
  ></script>
</head>
```
<!--kg-card-end: code-->

At this point, you have completed the majority of the web app setup process. The last thing you need to do is initialize an OneSignalSDK instance  

## Configuring Your Next App in OneSignal

Custom code integrations require a bit of JavaScript code to initialize OneSignal. I'm going to focus on HTTP initialization because more people will be able to follow along. HTTPS initialization is very similar to what I'm covering here, so this guide will still be helpful to you.

OneSignal needs a unique key called `appId` to initialize the SDK. You can obtain this key by logging into your [OneSignal account](https://app.onesignal.com/login).

If this is the first time you've logged into your OneSignal account, you will be presented with a welcome page asking you to configure the platform. Create a new app for the Web platform named **_OneSignal Next.js_** _by_ filling out the form and selecting _ **Web** _ as your platform.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-19_at_11.01.43_AM.png)<figcaption>Configuring new OneSignal app for the Web platform.</figcaption>

<!--kg-card-end: image-->

If you've already configured your OneSignal for other apps, you can create a new app by selecting **_+New App_** from the apps drop-down menu in your dashboard, as shown below.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/2021-05-19_11.22.17.gif)<figcaption>Select "New App" from the app dropdown menu in your OneSignal dashboard.</figcaption>

<!--kg-card-end: image-->

Once you've finished filling out the form, click **_Next: Configure Your Platform_**.

Under **_1. Choose Integration_** , select the _ **Custom Code** _ option and fill out the remaining form fields in the **_2._** _ **Site Setup** _ section.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-19_at_11.19.58_AM.png)<figcaption>Configuring a custom code web integration in OneSignal.</figcaption>

<!--kg-card-end: image-->

Note that I'm using `http://localhost:3000` for my site URL because my dev server serves the site there. Once you're ready to deploy your site, you would change this URL to point to your domain. You'll also want to double-check that you enable the _Local Testing_ option, allowing the integration to work in a development environment.

Lastly, click the **_Save_** to complete the application setup process.

The final page of the app creation process reveals `appId` in the second script. Copy the content of the second script.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/5.png)<figcaption>Script needed to initialize OneSignal SDK</figcaption>

<!--kg-card-end: image-->
## Initializing the OneSignal SDK

Next.js uses React to render the app, so I have to handle the initialization of the SDK in a way that works with the framework. React provides a mechanism to perform side effects on page load: `useEffect` (read the [doc](https://reactjs.org/docs/hooks-effect.html) to learn more). This hook allows code to execute when the page is mounted, which is necessary to init OneSignal.

<!--kg-card-begin: code-->

```javascript
useEffect(() => {
    window.OneSignal = window.OneSignal || [];
    OneSignal.push(function () {
        OneSignal.init({
            appId: "b40b7cc7-13dc-4662-8b48-efa668f9b72a",
            notifyButton: {
                enable: true,
            },

            allowLocalhostAsSecureOrigin: true,
        });
    });

    return () => {
        window.OneSignal = undefined;
    };
}, []); // <-- run this effect once on mount
```
<figcaption>This hook should be located in <code>_app.js</code></figcaption><!--kg-card-end: code-->

Reloading the app should reveal a new UI element (a circular red button with a bell at the center) at the bottom-right corner of the browser viewport.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/OneSignal---Next.js-app.png)<figcaption>The bell button is how site visitors can subscribe to receive notifications.</figcaption>

<!--kg-card-end: image-->
## Sending & Receiving Notifications

Now that you've finished the initialization process, you can create and send your first web push notification directly from your OneSignal dashboard. To test out this new messaging functionality, you'll first need to subscribe to receive notifications in your browser.

### Subscribing to Notifications

Subscribe to notifications by clicking on the red button at the bottom right of your screen.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-19_at_2.35.11_PM.png)<figcaption>Subscribe to notifications by clicking the button at the bottom right corner of your screen.</figcaption>

<!--kg-card-end: image-->

A dialogue box will appear at the top of your browser window asking you whether you would like to be shown notifications. Click _ **Allow** _ to subscribe.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-20_at_10.04.51_AM.png)<figcaption>Click "allow" to subscribe to notifications for your Next.js app.</figcaption>

<!--kg-card-end: image-->

To confirm your subscription, navigate to your [OneSignal account](https://app.onesignal.com/) and select the _ **OneSignal Nextjs** _ app. Click the **_Audience_** tab from the header menu to view subscribed users.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/onesignal-dashboard-audience-subscribed-users-screenshot.gif)<figcaption>View your subscriber list by selecting your Next.js app and navigating to the audience tab.</figcaption>

<!--kg-card-end: image-->

Select **_All Users_** from the sub-navigation menu to see a list of all subscribed users for this app.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/onesignal-dashboard-subscribed-users-page.png)<figcaption>The "All Users" tab shows a list of your current subscribed users.</figcaption>

<!--kg-card-end: image-->

At this point, you should be your only subscribed user 😅.

### Building Your Message

Now that you have a subscriber, you can use OneSignal to push a web notification. To build a new messaging campaign, selecting _ **Messages** _ from the main navigation menu and click the blue **_+_** _ **New Push** _ button on the top right corner of the screen.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen-Shot-2021-06-11-at-5.23.05-PM.png)<figcaption>Create a new web push notification in your OneSignal dashboard.</figcaption>

<!--kg-card-end: image-->

Fill out the form with your message content and message delivery preferences. You will see a preview of how your notification will look on the right side of your screen.  

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen_Shot_2021-05-20_at_10.47.17_AM.png)<figcaption>Build your push notification and preview how it will look.</figcaption>

<!--kg-card-end: image-->

For testing purposes, our notification is configured to send immediately. The notification preview shows what the message will look like for a Mac user who has subscribed to the site using Chrome. Click the **_Web: macOS button_** located below the preview image to see how your notification will look on different platforms.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/Screen-Shot-2021-06-11-at-5.08.30-PM.png)<figcaption>OneSignal's notification preview tool.</figcaption>

<!--kg-card-end: image-->

It's important to check the preview for all platforms before pushing a notification so that you can make any necessary formatting adjustments. Because this is a demo, I will push this notification even though the layout is broken for the Android web platform.

### Sending Your Notification

When you are finished previewing your notification, click **_Confirm Message_** to review your selections and click _ **Send Message** _ to send it to your subscribers (a.k.a yourself).

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/review-and-send-your-web-push-notification-onesignal-1.gif)<figcaption>Review and send your message.</figcaption>

<!--kg-card-end: image-->

You should see your notification appear on your desktop. If you entered a URL into the **_Launch URL_** form field of the message builder tool, then clicking on your notification should open a browser window with your designated URL destination. In my demo example, I entered the [GitHub address](https://github.com/OneSignal/OneSignal-Nextjs-Sample) for this integration guide.

<!--kg-card-begin: image-->

![How to Integrate OneSignal into a Next.js App](https://onesignal.com/blog/content/images/2021/06/view-web-notification-and-take-action-onesignal.gif)<figcaption>View your web push notification and click on it to trigger your specified action.</figcaption>

<!--kg-card-end: image-->

Congratulations! You've successfully completed the Next.js and OneSignal integration process and sent your first web push notification.

## Additional Support & Helpful Resources

To learn more about web push notifications and explore customization options, check out our [Web Push SDK documentation](https://documentation.onesignal.com/docs/web-push-sdk).

If you are using web notifications in a creative way to improve your Next app UX, we want to hear about it! Tag us in a Tweet **_@onesignal_** to share your use cases.

Still have questions or want some help getting started? Email us at **_support@onesignal.com_**.