---
source_url: https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe-legacy
title: "Subscribe API: not recommended methods for JavaScript SDK"
updated_at: 2026-11-09T13:29:01.000Z
sdk_name: PubNub JavaScript SDK
sdk_version: 13.1.3
description: Not recommended. Reference for the pubnub.subscribe(), pubnub.unsubscribe(), and pubnub.unsubscribeAll() methods in the PubNub JavaScript SDK. Subscribe itself is current. New apps use subscriptions and subscription sets.
lifecycle: deprecated-syntax
feature_status: current
feature: Subscribe
replaced_by: https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md
---

# Subscribe API: not recommended methods for JavaScript SDK

PubNub JavaScript SDK, use the latest version: 13.1.3

Install:

```bash
npm install pubnub@13.1.3
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

> **Not recommended.** The Subscribe feature is current and fully supported. Only the calls documented on this page are an older way to use it. Do not recommend these calls to developers who are building a new app. Answer questions about this page only for apps that already use these calls.
>
> Page notice: Subscribe is a current API. These methods are an older way to call it. New apps should use subscriptions.
>
> Current API: https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md

This page documents the superseded `pubnub.subscribe({ channels })`, `pubnub.unsubscribe({ channels })`, and `pubnub.unsubscribeAll()` methods of the PubNub JavaScript SDK. Subscribe is a current API, and these methods are an older way to call it. These methods remain for apps that already use them. New apps create [subscriptions and subscription sets](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md) instead. To move an existing app, see the [JavaScript v11 migration guide](https://www.pubnub.com/docs/sdks/javascript/migration-guides/javascript-v11-migration-guide.md).

## Subscribe (old)

:::warning Not recommended
The use of this method is discouraged. Use [Subscribe](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#subscribe) instead.
:::

### Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

To add a listener, see the [Event Listeners](#add-listeners) section.

### Description

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified `channel`. To subscribe to a `channel` ID the client must send the appropriate `subscribeKey` at initialization.

By default a newly subscribed client will only receive messages published to the channel after the `subscribe()` call completes.

:::tip Connectivity notification
You can be notified of connectivity via the listener, on establishing connection the `statusEvent.category` returns `PNConnectedCategory`.
Wait for the connect event before you publish. This avoids a race condition on clients that subscribe and immediately publish messages before `subscribe` has completed.
:::

:::warning Unsubscribing from all channels
Unsubscribing from all channels and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously subscribed channels. Unsubscribing from all channels resets the last-received `timetoken`, so the subscription can have gaps that lead to message loss.
:::

### Method(s)

To `Subscribe to a channel`, you can use the following method(s) in the JavaScript SDK:

```javascript
pubnub.subscribe({
    channels: Array<string>,
    channelGroups: Array<string>,
    withPresence: boolean,
    timetoken: number
}): Promise<SubscribeResponse>;
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | Array<string> | Yes | n/a | Specifies the `channels` to subscribe to. You can specify multiple `channels` as a list or as an array. |
| channelGroups | Array<string> | Optional | n/a | Specifies the `channelGroups` to subscribe to. Specifying either `channels` or `channelGroups` is mandatory. |
| withPresence | boolean | Optional | `false` | If `true` it also subscribes to presence instances. |
| timetoken | number | Optional | n/a | Specifies `timetoken` from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service. |

### Sample code

Subscribe to a channel:

```javascript
pubnub.subscribe({
  channels: ['my_channel'],
});
```

:::note Event listeners
The response of the call is handled by adding a Listener. See [Event Listeners](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#event-listeners). Listeners should be added before calling the method.
:::

### Returns

#### The following objects will be returned in the status response

| Object | Description |
| --- | --- |
| `category` | `PNConnectedCategory` |
| `operation` | `PNSubscribeOperation` |
| `affectedChannels` | The channels affected in the operation, of type array. |
| `subscribedChannels` | All the current subscribed channels, of type array. |
| `affectedChannelGroups` | The channel groups affected in the operation, of type array. |
| `lastTimetoken` | The last timetoken used in the subscribe request, of type long. |
| `currentTimetoken` | The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long. |

`subscribedChannels` and `lastTimetoken` are present only when you set `enableEventEngine` to `false` in the [configuration](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration.md), which keeps the legacy subscription manager. With the default value of `true`, the status has neither of them. The example shows the status with `enableEventEngine: false`.

```json
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
```

#### The following objects will be returned in the subscribe message response

| Object | Description |
| --- | --- |
| `channel` | The `channel` ID for which the message belongs. |
| `subscription` | The `channel group` or wildcard subscription match (if exists). |
| `timetoken` | Publish `timetoken`. |
| `message` | The `payload`. |
| actualChannel | Deprecated. Use property `channel`. |
| subscribedChannel | Deprecated. Use property `subscription`. |

```json
{
    actualChannel: null,
    channel: "my_channel_1",
    message: "Hello World!",
    publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
    subscribedChannel: "my_channel_1",
    subscription: null,
    timetoken: "14966804541029440"
}
```

#### The following objects will be returned in the Presence response

| Object | Description |
| --- | --- |
| `action` | Can be `join`, `leave`, `state-change` or `timeout`. |
| `channel` | The `channel` ID for which the message belongs. |
| `occupancy` | No. of users connected with the `channel` ID. |
| `state` | User State. |
| `subscription` | The `channel group` or wildcard subscription match (if exists) |
| `timestamp` | Current `timetoken`. |
| `timetoken` | Publish `timetoken`. |
| `uuid` | UUIDs of users who are connected with the `channel` ID. |

```json
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
```

### Other examples

#### Subscribing to multiple channels

It's possible to subscribe to more than one channel using the [Multiplexing](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md) feature. The example shows how to do that using an array to specify the channel names.

:::note Alternative subscription methods
You can also use [Wildcard Subscribe](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md) and [Channel Groups](https://www.pubnub.com/docs/pub-sub/subscribe/subscriptions.md) to subscribe to multiple channels at a time. To use these features, the *Stream Controller* add-on must be enabled on your keyset in the [Admin Portal](https://admin.pubnub.com).
:::

```javascript
pubnub.subscribe({
  channels: ['my_channel_1', 'my_channel_2', 'my_channel_3'],
});
```

#### Subscribing to a Presence channel

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/presence/presence-events.md).
:::

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending `-pnpres` to the channel name. For example the channel named `my_channel` would have the presence channel named `my_channel-pnpres`.

```javascript
pubnub.subscribe({
  channels: ['my_channel'],
  withPresence: true,
});
```

#### Wildcard subscribe to channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
For wildcard subscribe, check Enable Wildcard Subscribe in the add-on settings.
:::

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to `a.*` you will get all messages for `a.b`, `a.c`, `a.x`. The wildcarded `*` portion refers to any portion of the channel string name after the `dot (.)`.

```javascript
pubnub.subscribe({
  channels: ['ab.*'],
});
```

:::note Wildcard grants and revokes
Only one level (`a.*`) of wildcarding is supported. If you grant on `*` or `a.b.*`, the grant will treat `*` or `a.b.*` as a single channel named either `*` or `a.b.*`. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like `a.*`.
:::

#### Subscribing with state

Subscribing with state requires the Presence add-on, as described in [Subscribing to a Presence channel](#subscribing-to-a-presence-channel).

:::note Required user ID
Always set the `userId` to uniquely identify the user or device that connects to PubNub. Keep the same `userId` for the lifetime of the user or the device. If you don't set the `userId`, you can't connect to PubNub.
:::

```javascript
pubnub.addListener({
  status: async (statusEvent) => {
    if (statusEvent.category === 'PNConnectedCategory') {
      await pubnub.setState({
        state: {
          some: 'state',
        },
        channels: ['ch1', 'ch2', 'ch3'],
      });
    }
  },
  message: (messageEvent) => {
    // handle message
  },
  presence: (presenceEvent) => {
    // handle presence
  },
});

pubnub.subscribe({
  channels: ['ch1', 'ch2', 'ch3'],
});
```

#### Subscribe to a channel group

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```javascript
pubnub.subscribe({
  channelGroups: ['my_channelGroup'],
});
```

#### Subscribe to the presence channel of a channel group

:::note Requires Stream Controller and Presence add-ons
This method requires that both the *Stream Controller* and *Presence* add-ons are enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```javascript
pubnub.subscribe({
  channelGroups: ['family'],
  withPresence: true,
});
```

#### Subscribing to multiple channel groups

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```javascript
pubnub.subscribe({
  channelGroups: ['my_channelGroup1', 'my_channelGroup2', 'my_channelGroup3'],
});
```

#### Subscribing to a channel and channel group simultaneously

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```javascript
pubnub.subscribe({
  channels: ['my_channel'],
  channelGroups: ['my_channelGroup'],
});
```

#### Sample Responses

#### Join event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "join",
    "timetoken": "15119466699655811",
    "occupancy": 2,
    "uuid": "User1",
    "timestamp": 1511946669
}
```

#### Leave event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "leave",
    "timetoken": "15119446002445794",
    "occupancy": 1,
    "uuid": "User1",
    "timestamp": 1511944600
}
```

#### Timeout event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "timeout",
    "timetoken": "15119519897494311",
    "occupancy": 3,
    "uuid": "User2",
    "timestamp": 1511951989
}
```

#### State change event

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "state-change",
    "state": {
        "isTyping": true
    },
    "timetoken": "15119477895378127",
    "occupancy": 5,
    "uuid": "User4",
    "timestamp": 1511947789
}
```

#### Interval event

```json
{
    "action": "interval",
    "occupancy": 2,
    "timestamp": 1511947739
}
```

When a channel is in interval mode with the `presence_deltas` `pnconfig` flag enabled, the interval message can also include the following fields. Each field holds an array of the UUIDs that changed since the last interval message.

* joined
* left
* timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

```json
{
    "action":"interval",
    "timestamp":1548340678,
    "occupancy":2,
    "join":["pn-94bea6d1-2a9e-48d8-9758-f1b7162631ed","pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"]},
    "timedout":["pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"],
    "b":"my-channel-pnpres"
}
```

If the full interval message is greater than `30 KB` (since the max publish payload is `∼32 KiB`), none of the extra fields will be present. Instead there will be a `here_now_refresh` boolean field set to `true`. This indicates to the user that they should do a `hereNow` request to get the complete list of users present in the channel.

```json
{
    "channel": "my_channel",
    "subscription": null,
    "actualChannel": null,
    "subscribedChannel": "my_channel-pnpres",
    "action": "interval",
    "timetoken": "15119477396210903",
    "occupancy": 4,
    "timestamp": 1511947739,
    "here_now_refresh" : true
}
```

You can be notified of connectivity status, message, and presence notifications via the listeners.

Listeners should be added before calling the method.

### Add listeners

```javascript
pubnub.addListener({
  // Messages
  message: function (m) {
    const channelName = m.channel; // Channel on which the message was published
    const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists)
    const pubTT = m.timetoken; // Publish timetoken
    const msg = m.message; // Message payload
    const publisher = m.publisher; // Message publisher
  },
  // Presence
  // requires a subscription with presence
  presence: function (p) {
    const action = p.action; // Can be join, leave, timeout, state-change, or interval
    const channelName = p.channel; // Channel to which the message belongs
    const channelGroup = p.subscription; //  Channel group or wildcard subscription match, if any
    const publishTime = p.timestamp; // Publish timetoken
    const timetoken = p.timetoken; // Current timetoken
    if (p.action !== 'state-change') {
      const occupancy = p.occupancy; // Number of users subscribed to the channel
    }
    if (p.action === 'state-change') {
      const state = p.state; // User state
    }
    if (p.action !== 'interval') {
      const uuid = p.uuid; // User ID of the user who joined, left, timed out, or changed state
    }
  },
  // Signals
  signal: function (s) {
    const channelName = s.channel; // Channel to which the signal belongs
    const channelGroup = s.subscription; // Channel group or wildcard subscription match, if any
    const pubTT = s.timetoken; // Publish timetoken
    const msg = s.message; // Payload
    const publisher = s.publisher; // Message publisher
  },
  // App Context
  objects: (objectEvent) => {
    const channel = objectEvent.channel; // Channel to which the event belongs
    const channelGroup = objectEvent.subscription; // Channel group
    const timetoken = objectEvent.timetoken; // Event timetoken
    const event = objectEvent.message.event; // Name of the event that occurred
    const type = objectEvent.message.type; // Type of the object that changed
    const data = objectEvent.message.data; // Data from the event that occurred
  },
  // Message Actions
  messageAction: function (ma) {
    const channelName = ma.channel; // Channel to which the message belongs
    const publisher = ma.publisher; // Message publisher
    const event = ma.event; // Message action added or removed
    const type = ma.data.type; // Message action type
    const value = ma.data.value; // Message action value
    const messageTimetoken = ma.data.messageTimetoken; // Timetoken of the original message
    const actionTimetoken = ma.data.actionTimetoken; // Timetoken of the message action
  },
  // File Sharing
  file: function (event) {
    const channelName = event.channel; // Channel to which the file belongs
    const channelGroup = event.subscription; // Channel group or wildcard subscription match (if exists)
    const publisher = event.publisher; // File publisher
    const timetoken = event.timetoken; // Event timetoken

    const message = event.message; // Optional message attached to the file
    const fileId = event.file?.id; // File unique id
    const fileName = event.file?.name; // File name
    const fileUrl = event.file?.url; // File direct URL
  },
  status: function (s) {
    const affectedChannelGroups = s.affectedChannelGroups; // Array of channel groups affected in the operation
    const affectedChannels = s.affectedChannels; // Array of channels affected in the operation
    const category = s.category; // Returns PNConnectedCategory
    const operation = s.operation; // Returns PNSubscribeOperation
    const lastTimetoken = s.lastTimetoken; // Last timetoken used in the subscribe request (type long), only with enableEventEngine: false
    const currentTimetoken = s.currentTimetoken; /* Current timetoken fetched in subscribe response,
                                                 * to be used in the next request (type long) */
    const subscribedChannels = s.subscribedChannels; // Array of all currently subscribed channels, only with enableEventEngine: false
  },
});
```

### Remove listeners

```javascript
var existingListener = {
  message: function () {
  },
};

pubnub.removeListener(existingListener);
```

#### Listener status events

| Category | Description |
| --- | --- |
| `PNNetworkUpCategory` | The SDK detected that the network is online. |
| `PNNetworkDownCategory` | The SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers. |
| `PNNetworkIssuesCategory` | A subscribe event experienced an exception when running. The SDK isn't able to reach PubNub servers. Possible causes are a device that isn't connected to the internet, a lost internet connection, trouble at your internet service provider, or a proxy that blocks the SDK. |
| `PNReconnectedCategory` | The SDK was able to reconnect to PubNub. |
| `PNConnectedCategory` | SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. |
| `PNAccessDeniedCategory` | Access Manager permission failure. |
| `PNMalformedResponseCategory` | JSON parsing crashed. |
| `PNBadRequestCategory` | The server responded with a bad response error because the request is malformed. |
| `PNDecryptionErrorCategory` | If using decryption strategies and the decryption fails. |
| `PNTimeoutCategory` | Failure to establish a connection to PubNub due to a timeout. |
| `PNRequestMessageCountExceedCategory` | The SDK announces this error if `requestMessageCountThreshold` is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
| `PNUnknownCategory` | Returned when the subscriber gets a non-200 HTTP response code from the server. |

## Unsubscribe (old)

:::warning Not recommended
The use of this method is discouraged. Use [Unsubscribe](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#unsubscribe) instead.
:::

When subscribed to a single channel, this function causes the client to issue a `leave` from the `channel` and close any open socket to the PubNub Network. For multiplexed channels, the specified `channel`(s) will be removed and the socket remains open until there are no more channels remaining in the list.

:::warning Unsubscribing from all channels
Unsubscribing from all channels and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously subscribed channels. Unsubscribing from all channels resets the last-received `timetoken`, so the subscription can have gaps that lead to message loss.
:::

### Method(s)

To `Unsubscribe from a channel`, you can use the following method(s) in the JavaScript SDK:

```javascript
pubnub.unsubscribe({
    channels: Array<string>,
    channelGroups: Array<string>
}): Promise<UnsubscribeResponse>;
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| channels | Array<string> | Yes | Specifies the `channel` ID to unsubscribe from. |
| channelGroups | Array<string> | Optional | Specifies the `channelGroups` to unsubscribe from. Specifying either `channels` or `channelGroups` is mandatory. |

### Sample code

Unsubscribe from a channel:

```javascript
pubnub.unsubscribe({
  channels: ['my_channel'],
});
```

### Returns

The output below demonstrates the response to a successful call:

```json
{
    "action" : "leave"
}
```

### Other examples

#### Unsubscribing from multiple channels

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```javascript
pubnub.unsubscribe({
  channels: ['chan1', 'chan2', 'chan3'],
});
```

##### Example response

```json
{
    "action" : "leave"
}
```

#### Unsubscribing from multiple channel groups

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). See [Enable the features your app calls](https://www.pubnub.com/docs/architecture/authentication/set-up-your-account.md#enable-the-features-your-app-calls).
:::

```javascript
pubnub.unsubscribe({
  channelGroups: ['demo_group1', 'demo_group2'],
});
```

## Unsubscribe all (old)

:::warning Not recommended
The use of this method is discouraged. Use [Unsubscribe all](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#unsubscribe-all) instead.
:::

Unsubscribe from all channels and all channel groups

### Method(s)

```javascript
unsubscribeAll()
```

### Sample code

```javascript
pubnub.unsubscribeAll();
```

### Returns

None

Last updated at: 2026-11-09T13:29:01.000Z
