---
source_url: https://www.pubnub.com/docs/sdks/javascript/api-reference/mobile-push
title: Mobile Push Notifications API for JavaScript SDK
updated_at: 2026-06-12T11:25:31.752Z
sdk_name: PubNub JavaScript SDK
sdk_version: 11.0.2
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Mobile Push Notifications API for JavaScript SDK

PubNub JavaScript SDK, use the latest version: 11.0.2

Install:

```bash
npm install pubnub@11.0.2
```

The Mobile Push Notifications feature connects native PubNub publishing to third-party push services. Supported services include Google Android FCM (Firebase Cloud Messaging) and Apple iOS APNs (Apple Push Notification service).

To learn more, read about [Mobile Push Notifications](https://www.pubnub.com/docs/general/push/send).

:::note Supported and recommended asynchronous patterns
PubNub supports [Callbacks, Promises, and Async/Await](https://javascript.info/async) for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the error status, you must add the [try...catch](https://javascript.info/try-catch) syntax to your code.
:::

## Add a device to a push notifications channel

:::note Requires Mobile Push Notifications add-on
Enable Mobile Push Notifications for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Enable mobile push notifications on a set of channels.

### Method(s)

```javascript
pubnub.push.addChannels({
    channels: Array<string>,
    device: string,
    pushGateway: string,
    environment: string,
    topic: string
})
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | Array<string> | Yes |  | Channels to enable for push notifications. |
| device | string | Yes |  | Device token. |
| pushGateway | string | Yes |  | Accepted values: `apns2`, `fcm`. |
| environment | string | Optional | `development` | APNs environment. Accepted values: `development`, `production`. Required if `pushGateway` is `apns2`. |
| topic | string | Optional |  | APNs topic (bundle identifier). Required if `pushGateway` is `apns2`. |

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

#### Add device to channel

```javascript
import PubNub from 'pubnub';
// Initialize PubNub with your keys
const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});
```

```javascript
// Function to add a device to a channel for APNs2
try {
  const response = await pubnub.push.addChannels({
    channels: ['a', 'b'],
    device: 'niceDevice',
    pushGateway: 'apns2',
    environment: 'production',
    topic: 'com.example.bundle_id',
  });
  console.log('device added to channels response:', response);
} catch (error) {
  console.error(
    `Error adding device to channels: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}

// Function to add a device to a channel for FCM
try {
  const response = await pubnub.push.addChannels({
    channels: ['a', 'b'],
    device: 'niceDevice',
    pushGateway: 'fcm',
  });
  console.log('device added to channels response:', response);
} catch (error) {
  console.error(
    `Error adding device to channels: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Response

```javascript
{
    error: false,
    operation: 'PNPushNotificationEnabledChannelsOperation',
    statusCode: 200
}
```

## List push notifications channels for a device

:::note Requires Mobile Push Notifications add-on
Enable Mobile Push Notifications for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Get all channels with push notifications for the specified push token.

### Method(s)

```javascript
pubnub.push.listChannels({
    device: string,
    pushGateway: string,
    environment: string,
    topic: string
})
```

| Parameter | Description |
| --- | --- |
| `device` *Type: stringDefault: n/a | Device token. |
| `pushGateway` *Type: stringDefault: n/a | Accepted values: `apns2`, `fcm`. |
| `environment`Type: stringDefault: `development` | APNs environment. Accepted values: `development`, `production`. Required if `pushGateway` is `apns2`. |
| `topic`Type: stringDefault: n/a | APNs topic (bundle identifier). Required if `pushGateway` is `apns2`. |
| `start`Type: stringDefault: n/a | Start channel for pagination. Use the last channel from the previous page. |
| `count`Type: numberDefault: n/a | Number of channels to return. Maximum 1000; default 500. |

### Sample code

#### List channels for device

```javascript
// for APNs2
try {
  const response = await pubnub.push.listChannels({
    device: 'niceDevice',
    pushGateway: 'apns2',
    environment: 'production',
    topic: 'com.example.bundle_id',
  });
  console.log('listing channels for device response:', response);
  response.channels.forEach((channel: string) => {
    console.log(channel);
  });
} catch (error) {
  console.error(
    `Error listing channels for device: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}

// for FCM
try {
  const response = await pubnub.push.listChannels({
    device: 'niceDevice',
    pushGateway: 'fcm',
  });

  console.log('listing channels for device response:', response);

  response.channels.forEach((channel: string) => {
    console.log(channel);
  });
} catch (error) {
  console.error(
    `Error listing channels for device: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Response

```javascript
// Example of status
{
    error: false,
    operation: 'PNPushNotificationEnabledChannelsOperation',
    statusCode: 200
}

// Example of response
{
    channels: [ 'a', 'b' ]
}
```

## Remove a device from push notifications channels

:::note Requires Mobile Push Notifications add-on
Enable Mobile Push Notifications for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Disable push notifications on selected channels.

### Method(s)

```javascript
pubnub.push.removeChannels({
    channels: Array<string>,
    device: string,
    pushGateway: string,
    environment: string,
    topic: string
})
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array`<string>`Default: n/a | Channels to disable for push notifications. |
| `device` *Type: stringDefault: n/a | Device token. |
| `pushGateway` *Type: stringDefault: n/a | Accepted values: `apns2`, `fcm`. |
| `environment`Type: stringDefault: `development` | APNs environment. Accepted values: `development`, `production`. Required if `pushGateway` is `apns2`. |
| `topic`Type: stringDefault: n/a | APNs topic (bundle identifier). Required if `pushGateway` is `apns2`. |

### Sample code

#### Remove device from channel

```javascript
// for APNs2
try {
  const response = await pubnub.push.removeChannels({
    channels: ['a', 'b'],
    device: 'niceDevice',
    pushGateway: 'apns2',
    environment: 'production',
    topic: 'com.example.bundle_id',
  });

  console.log('removing device from channel response:', response);
} catch (error) {
  console.error(
    `Error removing device from channel: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}

// for FCM
try {
  const response = await pubnub.push.removeChannels({
    channels: ['a', 'b'],
    device: 'niceDevice',
    pushGateway: 'fcm',
  });

  console.log('removing device from channel response:', response);
} catch (error) {
  console.error(
    `Error removing device from channel: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Response

```javascript
{
    error: false,
    operation: 'PNPushNotificationEnabledChannelsOperation',
    statusCode: 200
}
```

## Remove a device from all push notifications channels

:::note Requires Mobile Push Notifications add-on
Enable Mobile Push Notifications for your key in the [Admin Portal](https://admin.pubnub.com/). See how to [enable add-on features](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-).
:::

Disable push notifications from all channels registered for the specified push token.

### Method(s)

```javascript
pubnub.push.deleteDevice({
    device: string,
    pushGateway: string,
    environment: string,
    topic: string
})
```

| Parameter | Description |
| --- | --- |
| `device` *Type: stringDefault: n/a | Device token. |
| `pushGateway` *Type: stringDefault: n/a | Accepted values: `apns2`, `fcm`. |
| `environment`Type: stringDefault: `development` | APNs environment. Accepted values: `development`, `production`. Required if `pushGateway` is `apns2`. |
| `topic`Type: stringDefault: n/a | APNs topic (bundle identifier). Required if `pushGateway` is `apns2`. |

### Sample code

#### Remove all mobile push notifications

```javascript
// for APNs2
try {
  const response = await pubnub.push.deleteDevice({
    device: 'niceDevice',
    pushGateway: 'apns2',
    environment: 'production',
    topic: 'com.example.bundle_id',
  });

  console.log('deleteDevice response:', response);
} catch (error) {
  console.error(
    `Error deleting device: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}

// for FCM
try {
  const response = await pubnub.push.deleteDevice({
    device: 'niceDevice',
    pushGateway: 'fcm',
  });

  console.log('deleteDevice response:', response);
} catch (error) {
  console.error(
    `Error deleting device: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

### Response

```javascript
{
    error: false,
    operation: 'PNPushNotificationEnabledChannelsOperation',
    statusCode: 200
}
```

## Push notification format configuration

Push notifications enforce specific message format requirements. Use these methods to configure your APNs and FCM mobile push notifications.

### APNS2Configuration

`APNS2` configuration type.

#### Method(s)

```javascript
type APNS2Configuration = {
    collapseId?: string,
    expirationDate?: Date,
    targets: Array<APNS2Target>
}
```

| Parameter | Description |
| --- | --- |
| `collapseId`Type: string | Collapse identifier (`apns-collapse-id`). |
| `expirationDate`Type: Date | Expiration (`apns-expiration`). |
| `targets` *Type: Array< [APNS2Target](#apns2target)> | Delivery targets. |

### APNSNotificationPayload

`APNSNotificationPayload` provides APNs-only options.

#### Properties

| Parameter | Description |
| --- | --- |
| `configurations`Type: Array< [APNSNotificationConfiguration](#apns2configuration)> | HTTP/2 APNs delivery configurations. |
| `notification`Type: Hash | User-visible key-value pairs. |
| `payload`Type: Hash | Platform-specific payload for additional data. |
| `silent`Type: Boolean | If true, omits `alert`, `sound`, and `badge`. |

### APNS2Target

`APNS2` configuration target type.

#### Method(s)

```javascript
type APNS2Target = {
    topic: string,
    environment?: 'development' | 'production',
    excludedDevices?: Array<string>
}
```

| Parameter | Description |
| --- | --- |
| `topic` *Type: stringDefault: n/a | APNs topic (bundle identifier). |
| `environment`Type: stringDefault: `development` | Accepted values: `development`, `production`. |
| `excludedDevices` *Type: ArrayDefault: n/a | Push tokens to exclude. |

### FCMNotificationPayload

`FCMNotificationPayload` provides FCM-only options.

#### Properties

| Parameter | Description |
| --- | --- |
| `notification`Type: Hash | User-visible key-value pairs. |
| `data`Type: Hash | Additional key-value data (stringify values). Must not include reserved keys (for example, `from`, `message_type`, keys starting with `google` or `gcm`). See the Firebase table. |
| `silent`Type: Boolean | If true, moves `notification` under `data`. |
| `icon`Type: String | Icon shown with the notification title. |
| `tag`Type: String | Identifier used to update/replace a prior notification. |
| `payload`Type: Hash | Platform-specific payload for additional data. |

### Cross-platform notifications payload

`NotificationsPayload` helps build multi-platform payloads and access platform-specific builders.

#### Method(s)

| Parameter | Description |
| --- | --- |
| `subtitle`Type: string | Additional context for the notification. |
| `badge`Type: number | Badge count for supported platforms. |
| `sound`Type: string | Sound name or file path to play. |
| `debugging`Type: boolean | Include device delivery debug info. |
| `apns`Type: [APNSNotificationPayload](#apnsnotificationpayload) | APNs-specific builder. |
| `fcm`Type: [FCMNotificationPayload](#fcmnotificationpayload) | FCM-specific builder. |

```javascript
PubNub.notificationPayload(
    title: string,
    body: string
)
```

| Parameter | Description |
| --- | --- |
| `title`Type: string | Title shown in the notification. |
| `body`Type: string | Body text shown under the title. |

```javascript
buildPayload(
    platforms: Array<string>
)
```

| Parameter | Description |
| --- | --- |
| `platforms` *Type: Array`<string>` | List of platforms for which payload should be added to final dictionary. Available: apns, apns2, fcm |

#### Sample code

Create notification payload builder with pre-defined notification title and body:

```javascript
const builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat");
const messagePayload = builder.buildPayload(['apns2', 'fcm']);
// add required fields to the payload
try {
  const response = await pubnub.publish({
    message: messagePayload,
    channel: 'chat-bot',
  });
  console.log('publish response:', response);
} catch (error) {
  console.error(
    `Error publishing message: ${error}.${
      (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''
    }`,
  );
}
```

```javascript
let builder = PubNub.notificationPayload('Chat invitation',
                                            'You have been invited to \'quiz\' chat');
```

#### Response

Hash with data, which can be sent with publish method call and trigger remote notifications for specified platforms.

#### Other examples

##### Generate simple notification payload for FCM and APNS

```javascript
const builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat");
builder.sound = 'default';

console.log(JSON.stringify(builder.buildPayload(['apns', 'fcm']), null, 2));
```

##### Generate simple notification payload for FCM and HTTP/2-based APNs (default configuration)

```javascript
import PubNub from '../lib/types';

const pubnub = new PubNub({
  publishKey: 'demo',
  subscribeKey: 'demo',
  userId: 'myUniqueUserId',
});

// snippet.simpleNotificationPayloadFCMandAPNS
const builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat");
builder.sound = 'default';

console.log(JSON.stringify(builder.buildPayload(['apns', 'fcm']), null, 2));
// snippet.end

// snippet.simpleNotificationPayloadFCMandAPNSH/2
const payloadBuilder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat");
payloadBuilder.apns.configurations = [{ targets: [{ topic: 'com.meetings.chat.app' }] }];
payloadBuilder.sound = 'default';

console.log(JSON.stringify(payloadBuilder.buildPayload(['apns2', 'fcm']), null, 2));
// snippet.end

// snippet.simpleNotificationPayloadFCMandAPNSH/2CustomConfiguration
const configuration = [
  {
    collapseId: 'invitations',
    expirationDate: new Date(Date.now() + 10000),
    targets: [{ topic: 'com.meetings.chat.app' }],
  },
];
const customConfigurationBuilder = PubNub.notificationPayload(
  'Chat invitation',
  "You have been invited to 'quiz' chat",
);
customConfigurationBuilder.apns.configurations = configuration;

console.log(JSON.stringify(customConfigurationBuilder.buildPayload(['apns2', 'fcm']), null, 2));
// snippet.end
```

##### Generate simple notification payload for FCM and HTTP/2-based APNs (custom configuration)

```javascript
const configuration = [
  {
    collapseId: 'invitations',
    expirationDate: new Date(Date.now() + 10000),
    targets: [{ topic: 'com.meetings.chat.app' }],
  },
];
const customConfigurationBuilder = PubNub.notificationPayload(
  'Chat invitation',
  "You have been invited to 'quiz' chat",
);
customConfigurationBuilder.apns.configurations = configuration;

console.log(JSON.stringify(customConfigurationBuilder.buildPayload(['apns2', 'fcm']), null, 2));
```

##### Output

```json
{
    "pn_apns": {
        "aps": {
            "alert": {
                "body": "Chat invitation",
                "title": "You have been invited to 'quiz' chat"
            }
        },
        "pn_push": [
            {
                "collapse_id": "invitations",
                "expiration": "2019-11-28T22:06:09.163Z",
                "targets": [
                    {
                        "environment": "development",
                        "topic": "com.meetings.chat.app"
                    }
                ],
                "version": "v2"
            }
        ]
    },
    "pn_fcm": {
        "notification": {
            "body": "You have been invited to 'quiz' chat",
            "title": "Chat invitation"
        }
    }
}
```

Example above show how to create notification payload which APNS will try to redeliver few times (if devices not active) and give up after **10** seconds since moment when it has been scheduled.

Additionally this invitation notification will be grouped along with other invitation notifications (using provided `collapse_id` as group identifier) and shown as one in notification center.

#### Returns

Configured and ready to use `NotificationsPayload` instance.

## Terms in this document

* **Channel** - A pathway for sending and receiving messages between devices, created automatically when you first use it, that can handle any number of users and messages for different communication needs, like 1-1 text chats, group conversations, and other data streaming.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Push token** - A device identifier issued by a push provider (APNs or FCM) used to register a device for receiving mobile push notifications.