---
source_url: https://www.pubnub.com/docs/chat/sdks/push-notifications
title: Push notifications (deprecated)
updated_at: 2026-06-15T12:11:48.321Z
---

> 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


# Push notifications (deprecated)

:::warning Use Chat SDKs
This documentation is deprecated. Use any of our dedicated [Chat SDKs](https://www.pubnub.com/docs/chat/overview) to quickly implement chat functionality in your application.
:::

Mobile Push Notifications feature enables you to easily integrate with third-party services including FCM (Firebase Cloud Messaging) and APNs (Apple Push Notification service) to trigger mobile push notifications.

Responding to a message immediately can make all the difference. If a prospective client is looking for information or a critical service is down, you want to be in the loop 24/7. You can use PubNub to send your users mobile push notifications to keep them up to date when their chat window is closed, they are not actively using your app, or even when they are offline. This way, your users can stay informed about important messages you don't want them to miss.

## Registering mobile device tokens

Mobile Push allows you to associate devices (push tokens) with channels. When a message is published to a push-enabled channel, all associated devices receive that message via their respective push service (FCM or APNs).

Note that you must first enable *Mobile Push Notifications* from the [Admin Portal](https://admin.pubnub.com/) to use them in your app. For more details on working with mobile push notifications, refer to our [Push Notification documentation](https://www.pubnub.com/docs/general/push/send).

### Retrieving device tokens

Before you can use either service, you must be registered to use Firebase Cloud Messaging (FCM) or the Apple Push Notification service (APNs).

Each device that runs your app has a unique *device token*, which you need to register to be able to send mobile push notifications. You can obtain the token from your user's device using either your native app, or Cordova/PhoneGap with the Cordova Push plugin.

**To retrieve an iOS device token**, follow this [Apple guide](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/HandlingRemoteNotifications.html#//apple_ref/doc/uid/TP40008194-CH6-SW1).

**To retrieve an Android registration token**, follow this [Google guide](https://firebase.google.com/docs/cloud-messaging/android/client).

### Adding a device token to channels

This method associates a device token with one or more channels.

#### Node.js

```js
// FCM
pubnub.push.addChannels(
  {
    channels: ["chats.room1", "chats.room2", "alerts.system"],
    device: deviceToken,
    pushGateway: "gcm",
  },
  function(status) {
    console.log(status);
  }
);

// APNs2
pubnub.push.addChannels(
  {
    channels: ["chats.room1", "chats.room2", "alerts.system"],
    device: deviceToken,
    pushGateway: "apns2",
    environment: "production", // Required for APNs2
    topic: "com.mycompany.mybundleid" // Required for APNs2
  },
  function(status) {
    console.log(status);
  }
);
```

#### Swift

```swift
// APNs2
pubnub.modifyAPNSDevicesOnChannels(
  byRemoving: [],
  thenAdding: ["chats.room1", "chats.room2", "alerts.system"],
  device: deviceToken,
  on: "com.mycompany.mybundleid",
  environment: .production
 ) { result in
  switch result {
    case let .success(response):
      print("Successful Push Modification Response: \(response)")

    case let .failure(error):
      print("Failed Push List Response: \(error.localizedDescription)")
  }
}
```

#### Java

```java
// FCM
pubnub.addPushNotificationsOnChannels()
  .pushType(PNPushType.FCM)
  .channels(Arrays.asList("chats.room1", "chats.room1", "alerts.system"))
  .deviceId(deviceToken)
  .async(result -> { /* check result */ });

// APNs2
pubnub.addPushNotificationsOnChannels()
  .pushType(PNPushType.APNS2)
  .channels(Arrays.asList("chats.room1", "chats.room1", "alerts.system"))
  .deviceId("deviceToken")
  .topic("com.mycompany.mybundleid")
  .environment("production")
  .async(result -> { /* check result */ });
```

#### C#

```csharp
// FCM
pubnub.AddPushNotificationsOnChannels()
  .PushType(PNPushType.FCM)
  .Channels(new string[] { "chats.room1", "chats.room2", "alerts.system" })
  .DeviceId(deviceToken)
  .Execute(new PNCallback<PNPushAddChannelResult>((r, s) => {
      // This does not return actionable data. Be sure to check the status
      // on the outcome of the operation by checking the status.isError().
  }));
```

#### Go

```go
// FCM
pn.AddPushNotificationsOnChannels().
    Channels([]string{"ch1"}).
    DeviceIDForPush("device_id").
    PushType(pubnub.PNPushTypeFCM).
    Execute()
```

### Removing a device token from channels

This method disassociates a device token from one or more channels.

#### Node.js

```js
// FCM
pubnub.push.removeChannels({
  channels: ['ch-1', 'ch-2'],
  device: 'myDeviceId',
  pushGateway: 'gcm',
}, (status) => {
  if (status.error) {
    console.log('operation failed w/ status: ', status);
  } else {
    console.log('operation done!');
  }
});

// APNs2
pubnub.push.removeChannels({
    channels: ['ch-1', 'ch-2'],
    device: 'myDeviceId',
    pushGateway: 'apns2',
    environment: 'production', // Required for APNs2
    topic: 'com.mycompany.mybundleid' // Required for APNs2
  },
  function(status) {
    console.log(status);
  }
);
```

#### Swift

```swift
// APNs2
pubnub.removeAPNSDevicesOnChannels(
  ["ch-1"],
  for: deviceToken,
  on: "com.app.bundle",
  environment: .production
 ) { result in
  switch result {
  case let .success(channels):
    print("The list of channels disabled for push: \(channels)")
  case let .failure(error):
    print("Failed Push List Response: \(error.localizedDescription)")
  }
}
```

#### Java

```java
// FCM
pubNub.removePushNotificationsFromChannels()
        .channels(Arrays.asList("ch-1", "ch-2"))
        .pushType(PNPushType.FCM)
        .deviceId("myDeviceId")
        .async(result -> { /* check result */ });
```

#### C#

```csharp
// FCM
pubnub.RemovePushNotificationsFromChannels()
    .DeviceId("myDeviceId")
    .Channels(new string[] {
        "ch-1",
        "ch-2"
    })
    .PushType(PNPushType.FCM)
    .Execute(new DemoPushRemoveChannel());

public class DemoPushRemoveChannel : PNCallback<PNPushRemoveChannelResult> {
    public override void OnResponse(PNPushRemoveChannelResult result, PNStatus status) {
    }
}
```

#### Go

```go
// FCM
pn.RemovePushNotificationsFromChannels().
    Channels([]string{"ch-1", "ch-2"}).
    DeviceIDForPush("myDeviceId").
    PushType(pubnub.PNPushTypeFCM).
    Execute()
```

## Publishing messages with push payloads

If you want to trigger mobile push notifications, include one or both endpoint keys (`pn_apns` or `pn_fcm`) in your message before you send it to PubNub. Users connected to PubNub channels receive the `message` portion of the payload, and each third-party endpoint receives the data encapsulated in its associated endpoint key:

* APNs devices receive only the data within the `pn_apns` key
* FCM devices receive only the data within the `pn_fcm` key

### JavaScript

```js
const messagePayload = {
   "pn_apns":{
      "aps":{
         "alert":{
            "title":"Chat invitation",
            "body":"John invited you to chat"
         }
      },
      "pn_push":[
         {
            "push_type":"alert",
            "targets":[
               {
                  "environment":"production",
                  "topic":"BUNDLE_ID_FOR_APP_1"
               }
            ],
            "version":"v2"
         }
      ]
   },
   "pn_fcm": {
      "notification": {
         "title": "Chat invitation",
         "body": "John invited you to chat"
      },
      "android": {
         "notification": {
            "sound": "default"
         }
      }
   },
   "text":"Hello all!"
};
pubnub.publish({
message: messagePayload,
channel: 'ch-1',
}, (status) => {
// Handle publish status
});
```

### Swift

```swift
let message = ["text": "John invited you to chat", "room": "chats.room1"]

let payload = PubNubPushMessage(
  apns: PubNubAPNSPayload(
    aps: APSPayload(alert: .object(.init(title: "Chat invite")), sound: .string("default")),
    pubnub: [.init(targets: [.init(topic: "com.example.chat", environment: .production)])],
    payload: ""
  ),
  fcm: PubNubFCMPayload(
    payload: "",
    target: .topic(""),
    notification: FCMNotificationPayload(title: "Chat invite", body: "John invited you to chat"),
    android: FCMAndroidPayload(notification: FCMAndroidNotification(sound: "default"))
  ),
  additional: message
)

print(payload)

// Publish on channel
pubnub.publish(
  channel: "inbox.user123",
  message: payload
) { result in
  switch result {
    case let .success(response):
      print("Successful Response: \(response)")

    case let .failure(error):
      print("Failed Response: \(error.localizedDescription)")
  }
}
```

### Java

```java
PushPayloadHelper pushPayloadHelper = new PushPayloadHelper();

// Set up FCM parameters (FCMPayload)
PushPayloadHelper.FCMPayload fcmPayload = new PushPayloadHelper.FCMPayload();
PushPayloadHelper.FCMPayload.Notification fcmNotification =
  new PushPayloadHelper.FCMPayload.Notification()
    .setTitle("Chat invite")
    .setBody("John invited you to chat");

fcmPayload.setNotification(fcmNotification);

// Set FCM payload
pushPayloadHelper.setFcmPayload(fcmPayload);

// Create the APS alert title/body
JsonObject apsAlertData = new JsonObject();
apsAlertData.addProperty("title", "Chat invite");
apsAlertData.addProperty("body", "John invited you to chat");

// Define APS
PushPayloadHelper.APNSPayload.APS aps = new PushPayloadHelper.APNSPayload.APS()
  .setAlert(apsAlertData)
  .setSound("default");

PushPayloadHelper.APNSPayload apnsPayload = new PushPayloadHelper.APNSPayload()
  .setAps(aps);

// Set APNs2 Configurations as a list
apnsPayload.setApns2Configurations(Arrays.asList(
  new PushPayloadHelper.APNSPayload.APNS2Configuration()
    .setVersion("v2")
    .setTargets(Arrays.asList(
      new PushPayloadHelper.APNSPayload.APNS2Configuration.Target()
        .setEnvironment(PNPushEnvironment.PRODUCTION)
        .setTopic("com.example.chat")
    ))));

// Set APNs payload
pushPayloadHelper.setApnsPayload(apnsPayload);

// Common payload for real-time PubNub subscribe
Map<String, Object> commonPayload = new HashMap<>();
commonPayload.put("text", "John invited you to chat");
commonPayload.put("room", "chats.room1");
pushPayloadHelper.setCommonPayload(commonPayload);

// Build the payload
// Returns a Map which can be used directly as the message for the pubnub.publish() method
Map<String, Object> payload = pushPayloadHelper.build();
System.out.println(payload);

// Publish on channel
pubnub.publish()
  .channel("inbox.user123")
  .message(payload)
  .async(result -> { /* check result */ });
```

### Unity

```csharp
Dictionary<string, string> payload = new Dictionary<string, string>();
payload.Add("pn_apns", "<apple payload>");
payload.Add("pn_gcm", "<google payload>");

pubnub.Publish()
    .Channel("chats.room1")
    .Message(payload)
    .Async((result, status) => {
        if (!status.Error) {
            Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
        } else {
            Debug.Log(status.Error);
            Debug.Log(status.ErrorData.Info);
        }

    });
```