How to Send Push Notifications with the OneSignal NodeJS Client SDK
Tags: node, backend, webdev, mobieldev
Published: 2022-06-06 19:18:17

---
title: How to Send Push Notifications with the OneSignal NodeJS Client SDK
published: true
date: 2022-05-13 16:25:56 UTC
tags: nodejs,backend,webdev,mobieldev
canonical_url: https://onesignal.com/blog/send-push-notifications-with-the-onesignal-nodejs-client-sdk/
---

 ![How to Send Push Notifications with the OneSignal NodeJS Client SDK](https://onesignal.com/blog/content/images/2022/05/send-push-notifications-with-onesignal-nodejs-client-sdk.jpg)

It’s no secret that push notifications can help you engage and retain app users. In this tutorial, we'll show you how to use the [OneSignal NodeJS Client SDK](https://github.com/OneSignal/node-onesignal) to interact with all the OneSignal functionalities that you have available in our [REST API](https://documentation.onesignal.com/reference/create-notification) but we made it easier for you with this wrapper.  
  
Using the OneSignal NodeJS Client SDK is very useful because it can help you integrate OneSignal into different workflows that your applications may have.

### Useful resources:

- [How to send push notification using the OneSignal REST API](https://onesignal.com/blog/how-to-send-push-notifications-with-the-onesignal-rest-api/)
- OneSignal [Postman Collection](https://www.postman.com/onesignaldevs/workspace/efc5736d-2ddf-45fd-8a5b-cd2dffa137f7/overview)
- [Tutorial Github Repo](https://github.com/OneSignalDevelopers/OneSignal-Node-Sample)

## OneSignal & Your Browser's Push API

The Push API gives applications the ability to receive messages from a server whether or not the app is in the foreground or currently loaded on a user agent. This lets you deliver asynchronous notifications and updates to users who opt-in, resulting in better engagement with timely new content.

This tutorial will cover an overview the usage of our API with the OneSignal NodeJS Client SDK.

### Guide Overview

- **[Part 1: OneSignal REST API Overview](#part-1-onesignal-rest-api-overview)**
- **[Part 2: Push Notification In NodeJS](#part-2-push-notifications-in-nodejs)**

This tutorial requires some basic knowledge of NodeJS and usage of REST APIs. I'm using the OneSignal Account along with:

- App with OneSignal integrated (mobile, web, or game)
- NPM (I’m using NPM version v6.14.11)
- NodeJS (I’m using NodeJS v16.14.2)

## **Part 1: OneSignal REST API Overview**

### Sending Notifications

The OneSignal Push API allows you to programmatically send [push notifications](https://documentation.onesignal.com/reference/create-notification). The push notifications can be sent to different [segments](https://documentation.onesignal.com/reference/create-notification#send-to-segments) (by default you send them to all subscribed users) and even specific devices using the User ID. Another cool feature of the OneSignal REST API is the ability to [cancel notifications](https://documentation.onesignal.com/reference/cancel-notification) that have been scheduled.

### View Notification

One of my favorite endpoints to use with the OneSignal REST API is the [view notification](https://documentation.onesignal.com/reference/view-notification) endpoint. This endpoint allows you to gather information about the notifications and outcomes associated with them. For example, the returned data can tell you see the number of notifications that have not been sent out, the number of notifications that got delivered, the number of confirmed deliveries, and much more information. If you want to learn more about all the [data returned](https://documentation.onesignal.com/reference/view-notification#returned-fields) by this endpoint visit our rest API reference **.**

Our API can do way more than just send a notification and view data from that notification. If you want to learn more about our whole REST API, visit the [OneSignal REST API overview](https://documentation.onesignal.com/docs/onesignal-api) page.

The cool thing about the NodeJS client library is that you don’t have to worry about the whole REST API setup in your NodeJS project, we handle all the boilerplate so you don’t have to worry about it ;)

### Creating Your NodeJS App

Inside of your terminal run the following commands to create a new NodeJS project using NPM:

```
npm init
```

After entering the previous npm command, answer all the questions that will appear on your terminal. These questions will generate the values of your `package.json`.

Your package.json file will look similar to this:

```
{
    "name": "myapp",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    “type”: “module”
    "scripts": {
    	"test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC"
}
```

Make sure you add the type property.

## Part 2: Push Notifications In NodeJS

### Setup your NodeJS App

The first thing you need to do is to create an index.js file. This file will contain all code necessary to send and view your notifications.

At the top of this file, add the request npm package. This package will help us make API calls to the OneSignal endpoints in an easier way than doing it with NodeJS natively.

`import * as OneSignal from '@onesignal/node-onesignal';`

Now, run `npm install @onesignal/node-onesignal --save` to add the `OneSignal NodeJS SDK Client` NPM package to your project. After you have installed the OneSignal NPM package, add the following variable to your index.js after the OneSignal import.

`const ONE_SIGNAL_APP_ID = 'ONESIGNAL_APP_ID';`

How to get the API KEY and the APP ID from OneSignal? Navigate to the OneSignal Dashboard, and navigate to the app you created inside of OneSignal. Once you have selected the app you want to work with during this how-to guide, the dashboard page will open up.

Navigate to the settings page, by clicking the **_S_** _ **ettings** _ tab.

![How to Send Push Notifications with the OneSignal NodeJS Client SDK](https://lh4.googleusercontent.com/4qwqoZc8i-RKk4is2mKr8nrIKRsSV1PnboJhGxXKUlj5Tuok4IUELJ9CpHzeBrFr8oGHYrN8hdn2pHh_dgNwVeBIRzrMvWE0SImD2LThOOOPg3XTDlj62SUP_Jan72H6KzjEiZ2_u0GoQCugNA)

Inside of settings, click on Keys & IDs. On this page, you will see your OneSignal App ID and your API key.

![How to Send Push Notifications with the OneSignal NodeJS Client SDK](https://lh4.googleusercontent.com/wuXFutPI4abItJPro3MH_QffVFrTHhjI6jAGgw4Y9k4E3Z6vQtZZmFpsfaNAQQfO6G_9gdIcER5VtT4Ws2DOt_VZMrDpV29-gChapuN86-QCwCkl6RVBKFWpVSVyQCFcoF8RtviR7fYVLZJOXg)

Now that you are in the **Settings > Keys & IDs** tab, you can copy the **OneSignal App ID** and the **REST API KEY**.

![How to Send Push Notifications with the OneSignal NodeJS Client SDK](https://lh3.googleusercontent.com/zNzceoQexrEGcuVuy-3T-Gh1453rTekJokLTYb4lcLnx3xJ-uTsoy0cc-tqZdytC992-DZH9R9zaqrY1jVUkqOsXLB_bm9S5LSUiet7RkEmxfNsH9JCi7Agoj4ORGCKNb8Dkz1onMgiMGNpTqg)

**Note:** Another quick way to access the OneSignal App ID is by copying it from the URL.

![How to Send Push Notifications with the OneSignal NodeJS Client SDK](https://lh6.googleusercontent.com/3PjhdZoDz9d-wt--4IdT8AG5oDY3soknq5LNrzCr5hqUTBAzrnqb3BwgQN5BdpknqDD-7VODior4T9uMoBE4VGO9zDQ26l4JpfKPDB6cgoDIX-28FYfBBrvrx12fRb05LhpO_LclHBcrc1Q-aA)

Keep in mind that if you want to create an app using the OneSignal NodeJS Client, you will need the [User Authentication Key](https://documentation.onesignal.com/docs/accounts-and-keys#user-auth-key).

### Token Builder

To authentificate the app, you will need to use your OneSignal REST API key. Create a key provider object with the function `getToken()` that returns your key.

**Returns:** Your key. In the background when you use this variable `app_key_provider.getToken()` gets executed.

```
const app_key_provider = {
    getToken() {
        return 'ONESIGNAL_REST_API_KEY';
    }
};
```

### **Client Configuration**

We can configure the client using the `createConfiguration()` function. The configuration object can be used to set the `app_key_provider` properties.

```
const configuration = OneSignal.createConfiguration({
    authMethods: {
        user_key: {
        	tokenProvider: user_key_provider
    	},
        app_key: {
        	tokenProvider: app_key_provider
        }
    }
});
const client = new OneSignal.DefaultApi(configuration);
```

### **Create Notification**

Create a push notification and send it to the users of your app.

To send a push notification, you will add the following function that will make a call to the OneSignal REST API. This function takes a body parameter that represents the information that the push notification will contain.

```
const notification = new OneSignal.Notification();
notification.app_id = ONESIGNAL_APP_ID;
notification.included_segments = ['Subscribed Users'];
notification.contents = {
	en: "Hello OneSignal!"
};
const {id} = await client.createNotification(notification);
```

Notice we use object destructuring to store the ID of the notification in a variable called ID.

### View a Notification

After you have sent a notification, view the notification information and outcomes associated with it using the notification id.

As you can see, I’m passing as the second parameter the `id` variable that contains the notification id after I have created the notification using the `createNotification()` method.

```
const response = await client.getNotification(ONESIGNAL_APP_ID, id);
```

### Run Your Code

Thanks to our `package.json`, you will be able to run your nodejs code by opening your terminal and typing `npm run start`. After running this command you should see a notification appearing on your device if and only if you subscribed to notifications from your website, game, or app that you created and registered it in the OneSignal Dashboard.

Feel free to test other [methods of the NodeJS Client SDK](https://github.com/OneSignal/node-onesignal/blob/main/apis/DefaultApi.ts) and let us know what you think!

Want to learn more about the OneSignal products and other technologies? Join our OneSignal Developers Community!

## Join the OneSignal Developers Community

The OneSignal Developer community is a group of passionate individuals who work with OneSignal products. Community members have the opportunity to expand their network and knowledge across different technologies.

### Connect on Twitter

Follow our [OneSignal Developers Twitter](https://twitter.com/OneSignalDevs) to learn more about OneSignal, technical tips, and the latest events from OneSignal developers.

### Join Our Discord Server

The OneSignal Developer community gathers on our public chat server, available on Discord. [Our Discord server](https://discord.gg/EP7gf6Uz7G) is a safe environment to network with other members, ask questions, and learn from each other. It is also a place to engage with the OneSignal product development team.