---
source_url: https://www.pubnub.com/docs/serverless/functions/functions-apis/pubnub-module
title: PubNub Module
updated_at: 2026-06-23T11:46:47.564Z
---

> 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


# PubNub Module

The `pubnub` module provides PubNub client API methods.

:::note Execution boundaries
1. You can chain up to `3` hops from one Function to another using `publish` or `fire`.
2. Within one Function execution, you can perform up to `3` combined operations: `KV store`, `XHRs`, `publish`, or `fire`.
:::

The `pubnub` module is made available via the following `require()` statement:

```javascript
const pubnub = require('pubnub');
```

## Publish

### Publish

Use the `publish()` method to send a message to subscribers and Functions.

#### Usage

```javascript
publish({ message, channel })
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| message | Object | Yes |  | The message to send. |
| channel | String | Yes |  | The channel to publish to. |

```javascript
pubnub.publish({
    "channel": "hello_universe",
    "message": request.message
}).then((publishResponse) => {
    console.log(`Publish Status: ${publishResponse[0]}:${publishResponse[1]} with TT ${publishResponse[2]}`);
});
```

:::note JSON requirement
Published payloads must be valid JSON. Strings won't trigger Functions.
:::

### Fire

Use the `fire()` method to trigger Functions without delivering to subscribers.

#### Usage

```javascript
fire({ message, channel })
```

| Parameter | Description |
| --- | --- |
| `message` *Type: Object | JavaScript object to be sent to PubNub. |
| `channel` *Type: String | The channel to publish to. |

```javascript
pubnub.fire({
    "channel": "hello_universe",
    "message": request.message
}).then((publishResponse) => {
    console.log(`Publish Status: ${publishResponse[0]}:${publishResponse[1]} with TT ${publishResponse[2]}`);
});
```

### Signal

To send a signal to PubNub Subscribers and Functions, use the `signal()` method.

By default, signals are limited to a message payload size of `64` bytes. This limit applies only to the payload and not to the URI or headers. If you require a larger payload size, [contact support](https://support.pubnub.com/hc/en-us/requests/new).

#### Usage

```javascript
signal({ message, channel })
```

| Parameter | Description |
| --- | --- |
| `message` *Type: Object | JavaScript object to be sent to PubNub. |
| `channel` *Type: String | The channel to publish to. |

```javascript
pubnub.signal({
    "channel": "hello_universe",
    "message": request.message // must be smaller than 64 bytes
}).then((signalResponse) => {
    console.log(`Signal Status: ${signalResponse[0]}:${signalResponse[1]} with TT ${signalResponse[2]}`);
});
```

:::note JSON requirement
Payload that is published via `signal` requires a valid `JSON`. Strings won't trigger Functions.
:::

## File sharing

At present, the main use case for Functions is to construct the URL and integrate with external services, for example, for image moderation or logging. To upload and download files, you need to use a [PubNub client SDK](https://www.pubnub.com/docs).

### List files in channel

Retrieve the list of files uploaded to a `channel`.

#### Usage

`listFiles` accepts a single argument — a Javascript object with the following properties:

```javascript
listFiles({ channel, limit, next })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | Retrieve list of files for this `channel`. |
| `limit`Type: NumberDefault: `100` | Number of files to return. |
| `next`Type: StringDefault: N/A | String token to get the `next` batch of files. |

```javascript
const pubnub = require('pubnub');

return pubnub.listFiles({
    channel: 'my_channel',
    limit: 2,
    next: '10rX15WW7pyYsbwPY2h3ZlPfP1vSFl_3M6rCappuuCSULLIQb3MWOOba7xouJDxxs8yS9Ql6mxdz-1FmMdeiUE53GPMjNLmrUtefZdhoaswVwat7Z0Q6YzXi4FQYclt7pW_nQlOaC-vzaGSaeSB4QeQS2vlmjyiDVFYPQvSz6g39X7__1H73-XgogHZqqI-jnWMonp2fpgcQ',
}).then((res) => {
    console.log(res);
}).catch((err) => {
    // handle error
});
```

#### Returns

Returns a promise that resolves to an object with the following format:

```javascript
{
  status: number,
  data: Array<{
    name: string,
    id: string,
    size: number,
    created: string
  }>,
  next: string,
  count: number,
}
```

For example:

```javascript
{
  status: 200,
  data: [
      {
        name: 'cat_picture.jpg',
        id: '0936618c-94f9-4e96-bd9c-aa4fd8719c28',
        size: 31,
        created: '2020-08-13T19:05:30Z'
      },
      {
        name: 'my_other_file.jpg',
        id: '2afb0f85-8eb3-43bf-84f9-5b4c7e031f8f',
        size: 23,
        created: '2020-08-13T19:07:22Z'
      },
  ],
  next: "1NrsIonxYtGgsxNA3_Klt6jxt235cJUKY3hRNXkRP1TlHrzCSPj0yhysBgb04dRtwtkeR7lxcKyq-Y-CU7wxB1Tplf-NaW3mFYrzV5DDhGK7WEuT3FIBpg8RfA2rIScBhLJ-3Jaqthf9SKKU2fJzkPdPgwdz7yJvrfWrmsyXzZblbprUXl_HWaUKv4aE7_wP-91Nz_xpwM84",
  count: 2,
}
```

### Get file URL

Get a file's direct download URL. This method doesn't make any API calls, and won't decrypt an encrypted file.

#### Usage

`getFileUrl` accepts a single argument — a Javascript object with the following properties:

```javascript
getFileUrl({ channel, id, name })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | `Channel` that the file was sent to. |
| `id` *Type: String | The file's unique identifier. |
| `name` *Type: String | `Name` of the file. |

```javascript
const pubnub = require('pubnub');

const url = pubnub.getFileUrl({
    channel: 'my_channel',
    id: '12345678-1234-5678-123456789012',
    name: 'cat_picture.jpg',
});

console.log(url);
```

#### Returns

Returns a string with the following format:

```javascript
'https://ps.pndsn.com/v1/files/my-subkey/channels/my_channel/files/12345678-1234-5678-123456789012/cat_picture.jpg'
```

### Delete file

Deletes a file from the specified channel.

#### Usage

`deleteFile` accepts a single argument — a Javascript object with the following properties:

```javascript
deleteFile({ channel, id, name })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | `Channel` that the file was sent to. |
| `id` *Type: String | The file's unique identifier. |
| `name` *Type: String | `Name` of the file. |

```javascript
const pubnub = require('pubnub');

return pubnub.deleteFile({
    channel: 'my_channel',
    id: '12345678-1234-5678-123456789012',
    name: 'cat_picture.jpg' ,
}).then((res) => {
    console.log(res);
}).catch((err) => {
    // handle error
});
```

#### Returns

Returns a promise that resolves to an object with the following format:

```javascript
{
  status: 200,
}
```

### Publish file message

Manually publish information about a previously uploaded file.

#### Usage

`publishFile` accepts a single argument — a Javascript object with the following properties:

```javascript
publishFile({ message, channel, fileId, fileName, storeInHistory, ttl, meta })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | `Channel` on which to send the file message. |
| `fileId` *Type: StringDefault: N/A | The file's unique identifier. |
| `fileName` *Type: StringDefault: N/A | `Name` of the file. |
| `message`Type: ObjectDefault: N/A | Message to attach to the file. The message can be any value that can be JSON-stringified. |
| `storeInHistory`Type: BooleanDefault: `true` | Whether published file messages should be stored in the channel's history. If `storeInHistory` isn't specified, then the history configuration on the key is used. |
| `ttl`Type: NumberDefault: N/A | How long the message should be stored in the channel's history, in hours. If not specified, defaults to the keyset's retention value. |
| `meta`Type: ObjectDefault: N/A | Additional metadata published with the message. |

```javascript
const pubnub = require('pubnub');

return pubnub.publishFile({
    channel: 'my_channel',
    fileId: '12345678-1234-5678-123456789012',
    fileName: 'cat_picture.jpg',
    message: {
        someField: 'someValue',
    },
}).then((res) => {
    console.log(res);
}).catch((err) => {
    // handle error
});
```

#### Returns

Returns a promise that resolves to an object with the following format:

```javascript
[ 1, "Sent", "15973568884237770" ]
```

## Presence

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) 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/general/presence/presence-events#subscribe-to-presence-channel).
:::

### Here now

To fetch Here Now, use the `hereNow()` method.

#### Usage

```javascript
hereNow({ channels, channelGroups, includeUUIDs, includeState })
```

| Parameter | Description |
| --- | --- |
| `channels`Type: Array | `channels` is an array which specifies the `channels` to return occupancy results. |
| `channelGroups`Type: Array | `channelGroups` is an array which specifies the `channelGroup` to return occupancy results. |
| `includeUUIDs`Type: Boolean | Setting `includeUUIDs` to `false` disables the return of UUIDs. |
| `includeState`Type: Boolean | Setting `includeState` to `true` enables the return of subscriber state information. |

```javascript
pubnub.hereNow({
    channels: ["ch1"],
    channelGroups : ["cg1"],
    includeUUIDs: true,
    includeState: true
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Where now

To fetch Where Now, use the `whereNow()` method.

#### Usage

```javascript
whereNow({ uuid })
```

| Parameter | Description |
| --- | --- |
| `uuid`Type: String | `uuid` specifies the UUID to return channel list for. |

```javascript
pubnub.whereNow({
    uuid: "uuid"
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Global here now

To fetch Global Here Now, use the `hereNow()` method.

#### Usage

```javascript
hereNow({ includeUUIDs, includeState })
```

| Parameter | Description |
| --- | --- |
| `includeUUIDs`Type: Boolean | Setting `includeUUIDs` to `false` disables the return of UUIDs. |
| `includeState`Type: Boolean | Setting `includeState` to `true` enables the return of subscriber state information. |

```javascript
pubnub.hereNow({
    includeUUIDs: true,
    includeState: true
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Set state

To fetch Set State, use the `setState()` method.

#### Usage

```javascript
setState({ channels, channelGroups, state, uuid })
```

| Parameter | Description |
| --- | --- |
| `channels`Type: Array | Specifies the `channels` to get the state. Either `channels` or `channelGroups` should be provided. |
| `channelGroups`Type: Array | Specifies the `channelGroups` to get the state. Either `channels` or `channelGroups` should be provided. |
| `state`Type: Object | `state` is a JSON object of key/value pairs with supported `data-types` of int, float, and string. Nesting of key/values is not permitted and key names beginning with the `pn` prefix are reserved. |
| `uuid`Type: String | `uuid` to set the current state. |

```javascript
pubnub.setState({
    channels: ['ch1'],
    channelGroups: ['cg1'],
    state: newState,
    uuid: "uuid"
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Get state

To fetch Set State, use the `getState()` method.

#### Usage

```javascript
getState({ uuid, channels, channelGroups })
```

| Parameter | Description |
| --- | --- |
| `uuid`Type: String | `uuid` is the subscriber UUID to get the current state. |
| `channels`Type: Array | Specifies the `channels` to get the state. Either `channels` or `channelGroups` should be provided. |
| `channelGroups`Type: Array | Specifies the `channelGroups` to get the state. Either `channels` or `channelGroups` should be provided. |

```javascript
pubnub.getState({
    uuid: "uuid",
    channels: ['ch1'],
    channelGroups: ['cg1']
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

## Access Manager

:::note Requires Access Manager
This method requires that **Access Manager** is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

### Grant

To grant permissions in [Access Manager v2](https://www.pubnub.com/docs/general/security/access-control-v2), use the `grant()` method.

:::note Required secret key
Only server-side instances with a valid secret key can grant permissions to PubNub resources.
:::

#### Usage

```javascript
grant({ channels, channelGroups, uuids, authKeys, ttl, read, write, manage, delete, get, update, join})
```

| Parameter | Description |
| --- | --- |
| `channels`Type: Array | Array which specifies the channel(s) to grant permissions to. |
| `channelGroups`Type: Array | Array which specifies the channel group(s) to grant permissions to. |
| `uuids`Type: Array | Array which specifies the UUID(s) to grant permissions to. You can't grant permissions to channels or channel groups in the same request if you decide to use `uuids`. This parameter does **not** support wildcards. |
| `authKeys`Type: Array | Array which specifies the authorization credentials that should be granted access to selected resources. `authKeys` are required for user-level grants. If you don't specify this parameter, the permissions will apply to all clients on the channel-level or application-level. |
| `ttl` *Type: Number | Time in minutes for which granted permissions are valid. The default value is `1440 (24hrs)` and the allowed values range from `1` to `525600`. If you set `ttl` to `0`, it will apply the grant indefinitely. |
| `read`Type: Boolean | Set to `true` to grant `read` permissions. Set to `false` to remove permissions. |
| `write`Type: Boolean | Set to `true` to grant `write` permissions. Set to `false` to remove permissions. |
| `manage`Type: Boolean | Set to `true` to grant `manage` permissions. Set to `false` to remove permissions. |
| `delete`Type: Boolean | Set to `true` to grant `delete` permissions. Set to `false` to remove permissions. |
| `get`Type: Boolean | Set to `true` to grant `get` permissions. Set to `false` to remove permissions. |
| `update`Type: Boolean | Set to `true` to grant `update` permissions. Set to `false` to remove permissions. |
| `join`Type: Boolean | Set to `true` to grant `join` permissions. Set to `false` to remove permissions. |

:::note Max number of resources
There is a limit of up to 200 resources of the same type that you can request access to in a single grant API call.
:::

```javascript
pubnub.grant({
    channels: [ch1, ch2],
    channelGroups: [cg1, cg2],
    authKeys: [key1, key2],
    ttl: 12313,
    read: true,
    write: true,
    manage: true
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Grant token

To grant channel, channel group, and UUID permissions in [Access Manager v3](https://www.pubnub.com/docs/general/security/access-control), use the `grantToken()` method.

:::note Required secret key
Only server-side instances with a valid secret key can grant permissions to PubNub resources.
:::

#### Usage

```javascript
grantToken({ ttl, authorizedUuid, resources, patterns, meta })
```

| Parameter | Description |
| --- | --- |
| `ttl` *Type: Number | Total number of minutes for which the token is valid. The minimum allowed value is 1., The maximum is 43,200 minutes (30 days). |
| `authorizedUuid`Type: String | Single `uuid` which is authorized to use the token to make API requests to PubNub. |
| `resources`Type: Object | Object containing resource permissions. |
| `resources.uuids`Type: Object | Object containing `uuid` metadata permissions. For example, `{"uuid-1": {get: true, update: true, delete: true},"uuid-2": {...}}`. |
| `resources.channels`Type: Object | Object containing channel permissions. For example, `{"channel-id-1": {read: true, write: true, manage: true, delete: true, get: true, update: true, join: true},"channel-id-2": {...}}`. |
| `resources.groups`Type: Object | Object containing channel group permissions. For example, `{"group-id-1": {read: true, manage: true},"group-id-2": {...}}`. |
| `patterns`Type: Object | Object containing permissions to multiple resources specified by a RegEx pattern. |
| `patterns.uuids`Type: Object | Object containing `uuid` metadata permissions to apply to all `uuid`s matching the RegEx pattern. For example, `{"uuid-pattern-1": {get: true, update: true, delete: true},"uuid-pattern-2": {...}}`. |
| `patterns.channels`Type: Object | Object containing channel permissions to apply to all `channel`s matching the RegEx pattern. For example, `{"channel-pattern-1": {read: true, write: true, manage: true, delete: true, get: true, update: true, join: true}, "channel-pattern-2": {...}}`. |
| `patterns.groups`Type: Object | Object containing channel group permissions to apply to all channel groups matching the pattern. For example, `{"group-pattern-1": {read: true, manage: true}, "group-pattern-2": {...}}`. |
| `meta`Type: Object | Extra metadata to be published with the request. Values must be scalar only; arrays or objects aren't supported. |

:::note Required key/value mappings
For a successful grant request, you must specify permissions for at least one `uuid`, `channel`, or `group`, either as a resource sequence (`resources`) or as a regular expression (`patterns`).
:::

```javascript
pubnub.grantToken(
    {
        ttl: 15,
        authorizedUuid: "my-authorized-uuid",
        resources: {
            channels: {
                "channel-a": {
                    read: true
                },
                "channel-b": {
                    read: true,
                    write: true
                },
                "channel-c": {
                    read: true,
                    write: true
                },
                "channel-d": {
                    read: true,
                    write: true
                }
            },
            groups: {
                "channel-group-b": {
                    read: true
                }
            },
            uuids: {
                "uuid-c": {
                    get: true
                },
                "uuid-d": {
                    get: true,
                    update: true
                }
            }
        },
        patterns: {
            channels: {
            "^channel-[A-Za-z0-9]$": {
                read: true
            }
            }
        }
    },
    function (status, token) {
        console.log(token)
    });
```

### Revoke token

The `revokeToken()` method is used by the server to revoke access to PubNub resources previously granted using the `grantToken()` method.

This method only applies to [Access Manager v3](https://www.pubnub.com/docs/general/security/access-control).

:::note Required secret key
Only server-side instances with a valid secret key can revoke permissions to PubNub resources.
:::

#### Usage

```javascript
revokeToken(token)
```

| Parameter | Description |
| --- | --- |
| `token` *Type: String | Current token with embedded permissions. |

```javascript
pubnub.revokeToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")
```

### Parse token

The `parseToken()` method decodes an existing token and returns the object containing permissions embedded in that token. The client can use this method for debugging to check the permissions to the resources or find out the token's `ttl` details.

This method only applies to [Access Manager v3](https://www.pubnub.com/docs/general/security/access-control).

#### Usage

```javascript
parseToken(token)
```

| Parameter | Description |
| --- | --- |
| `token` *Type: String | Current token with embedded permissions. |

```javascript
pubnub.parseToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")
```

### Set token

The `setToken()` method is used by the client devices to update the authentication token granted by the server.

This method only applies to [Access Manager v3](https://www.pubnub.com/docs/general/security/access-control).

#### Usage

```javascript
setToken(token)
```

| Parameter | Description |
| --- | --- |
| `token` *Type: String | Current token with embedded permissions. |

```javascript
pubnub.setToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")
```

## Channel groups

:::note Requires Stream Controller
This method requires that **Stream Controller** is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

### Add channels

To add channels to a channel group, use `channelGroups.addChannels()`.

:::note Maximum number of channels
`200 channels` can be added to the `channel group` per one API call.
:::

#### Usage

```javascript
channelGroups.addChannels({ channels, channelGroup })
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array | `channels` is an array that specifies channels to be added to a channel group. |
| `channelGroup` *Type: String | `channelGroup` is a string that specifies the channel group to which you can add channels. |

```javascript
pubnub.channelGroups.addChannels({
    channels: ['ch1', 'ch2'],
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### List channels

To list all the channels of the channel group, use `channelGroups.listChannels()`.

#### Usage

```javascript
channelGroups.listChannels({ channels })
```

| Parameter | Description |
| --- | --- |
| `channelGroup` *Type: String | `channelGroup` is a string that specifies the channel group from which you want to list the channel(s). |

```javascript
pubnub.channelGroups.listChannels({
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Remove channels

To remove the channels from the channel group, use `channelGroups.removeChannels()`.

#### Usage

```javascript
channelGroups.removeChannels({ channels, channelGroup })
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array | `channels` is an array that specifies channels to remove from the channel group. |
| `channelGroup` *Type: String | `channelGroup` is a string that specifies the channel group from which you want to remove channels. |

```javascript
pubnub.channelGroups.removeChannels({
    channels: ['ch1'],
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Delete channel group

To remove the channel group, use `channelGroups.deleteGroup()`.

#### Usage

```javascript
channelGroups.deleteGroup({ channelGroup })
```

| Parameter | Description |
| --- | --- |
| `channelGroup` *Type: String | `channelGroup` is a string that specifies the channel group to remove. |

```javascript
pubnub.channelGroups.deleteGroup({
    channelGroup: 'myChannelGroup'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

## Message persistence

:::warning Requires Message Persistence
This method requires that **Message Persistence** is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/).
:::

### History

To fetch History, use the `history()` method.

#### Usage

```javascript
history({ channel, reverse, count, stringifiedTimeToken, start, end })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Specifies `channel` to return history messages from. |
| `reverse`Type: Boolean | Setting to `true` will traverse the timeline in `reverse` starting with the oldest message first. If both `start` and `end` arguments are provided, `reverse` is ignored and messages are returned starting from the newest `message`. |
| `count`Type: Number | Specifies the number of historical `messages` to return. |
| `stringifiedTimeToken`Type: Boolean | If `stringifiedTimeToken` is specified as `true`, the SDK will return `timetoken` values as strings instead of integers. This setting is encouraged in JavaScript environments which perform round-up/down on large integers. |
| `start`Type: String | Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. |
| `end`Type: String | Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. |

```javascript
export default (request) => {
    var pubnub = require('pubnub');

    return pubnub.history({
        'channel' : 'my_channel',
        'count' : 3,
        'stringifiedTimeToken' : true,
        'reverse' : true,
    }).then((response) => {
        console.log("startTT", response.startTimeToken);
        console.log("endTT", response.endTimeToken);
        response['messages'].forEach((value, index) => {
            console.log("message:", value.entry, "timetoken:", value.timetoken);
        });
        return request.ok();
    });
};
```

### Batch history

To fetch History from multiple channels, use the `fetchMessages()` method.

#### Usage

```javascript
fetchMessages({ channels, count, start, end, stringifiedTimeToken })
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array | Specifies `channels` to return history messages from. |
| `count`Type: Number | Specifies the number of historical `messages` to return per channel. |
| `start`Type: String | Timetoken delimiting the `start` of `time` slice (exclusive) to pull messages from. |
| `end`Type: String | Timetoken delimiting the `end` of `time` slice (inclusive) to pull messages from. |
| `stringifiedTimeToken`Type: Boolean | If `stringifiedTimeToken` is specified as true, the SDK will return `timetoken` values as a strings instead of integers. |

```javascript
pubnub.fetchMessages({
    'channels' : ['my_channel', 'my_other_channel'],
    'count' : 8,
    'start' : '15343325214676133',
    'end' : '15343325004275466',
    'stringifiedTimeToken' : true,
}).then((status, response) => {
    console.log(status);
    console.log(response);
});
```

### Delete messages from history

To delete messages from the history, use the `deleteMessages()` method.

:::note Required setting
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable `Delete-From-History` checkbox in the key settings for your key in the Admin Portal.
Requires Initialization with a secret key.
:::

#### Usage

```javascript
deleteMessages({ channel, start, end })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Specifies `channel` messages to be deleted from history. |
| `start`Type: String | Timetoken delimiting the `start` of `time` slice (inclusive) to delete messages from. |
| `end`Type: String | Timetoken delimiting the `end` of `time` slice (exclusive) to delete messages from. |

```javascript
pubnub.deleteMessages({
    'channel' : 'my_channel',
    'start': '15088506076921021',
    'end': '15088532035597390',
}).then((result) => {
    console.log(result);
});
```

### Message counts

Specifies the number of historical messages to return per channel. The returned count is the number of messages in history with a timetoken value greater than the passed value in the `channelTimetokens` parameter.

#### Usage

```javascript
messageCounts({ channels, channelTimetokens })
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array | The `channels` to fetch the message count. |
| `channelTimetokens` *Type: Array | List of timetokens in the order of the channels list. Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens must be the same length as the list of channels, or the Function returns a `PNStatus` with an error flag. |

```javascript
pubnub.messageCounts({
    'channels' : ['my_channel', 'my_other_channel'],
    'channelTimetokens' : ['my_timetoken', 'my_other_timetoken'],
}).then((status, results) => {
    console.log(status);
    console.log(results);
});
```

## Mobile push

:::note Requires Mobile Push Notifications
This method requires that **Mobile Push Notifications** is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

### Add device to channel

To enable mobile push notifications on a provided set of channels, use `push.addChannels()`.

#### Usage

```javascript
push.addChannels({ channels, device, pushGateway, topic, environment })
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array | Specifies channels to associate with mobile push notifications. |
| `device` *Type: String | The device ID to associate with mobile push notifications. |
| `pushGateway` *Type: String | `apns2` or `fcm` |
| `topic`Type: String | The bundle identifier of your app. Required when using `apns2`. |
| `environment`Type: String | APNs environment: `development` or `production`. Defaults to `development`. |

```javascript
pubnub.push.addChannels({
    channels: ['my_channel', 'my_other_channel'],
    device: 'nice_device',
    pushGateway: 'apns2',
    topic: 'com.example.myapp'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### List channels for device

To request all channels on which push notifications were enabled, use `push.listChannels()`.

#### Usage

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

| Parameter | Description |
| --- | --- |
| `device` *Type: String | The device ID to associate with mobile push notifications. |
| `pushGateway` *Type: String | `apns2` or `fcm` |
| `topic`Type: String | The bundle identifier of your app. Required when using `apns2`. |
| `environment`Type: String | APNs environment: `development` or `production`. Defaults to `development`. |

```javascript
pubnub.push.listChannels({
    device: 'nice_device',
    pushGateway: 'apns2',
    topic: 'com.example.myapp'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Remove device from channel

To disable mobile push notifications on a provided set of channels, use `push.removeChannels()`.

#### Usage

```javascript
push.removeChannels({ channels, device, pushGateway, topic, environment })
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: Array | Specifies channels to associate with mobile push notifications. |
| `device` *Type: String | The device ID to associate with mobile push notifications. |
| `pushGateway` *Type: String | `apns2` or `fcm` |
| `topic`Type: String | The bundle identifier of your app. Required when using `apns2`. |
| `environment`Type: String | APNs environment: `development` or `production`. Defaults to `development`. |

```javascript
pubnub.push.removeChannels({
    channels: ['my_channel', 'my_other_channel'],
    device: 'nice_device',
    pushGateway: 'apns2',
    topic: 'com.example.myapp'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Remove all mobile push notifications

To disable mobile push notifications from all channels which are registered with a specified `pushToken`, use `push.deleteDevice()`.

#### Usage

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

| Parameter | Description |
| --- | --- |
| `device` *Type: String | The device ID to associate with mobile push notifications. |
| `pushGateway` *Type: String | `apns2` or `fcm` |
| `topic`Type: String | The bundle identifier of your app. Required when using `apns2`. |
| `environment`Type: String | APNs environment: `development` or `production`. Defaults to `development`. |

```javascript
pubnub.push.deleteDevice({
    device: 'nice_device',
    pushGateway: 'apns2',
    topic: 'com.example.myapp'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

## App Context

### Get metadata for all users

Returns a paginated list of UUID metadata objects, optionally including the custom data object for each.

#### Usage

```javascript
getAllUUIDMetadata({include, filter, sort, limit, page})
```

| Parameter | Description |
| --- | --- |
| `include`Type: ObjectDefault: N/A | Include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllUUIDMetadata({
        limit: 1,
        include: {
            customFields: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched uuid metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch uuid metadata');
    });
};
```

#### Response

```json
{
   "status" : 200,
   "data" : [
      {
         "name" : "my-name",
         "updated" : "2020-07-16T21:10:38.770048Z",
         "id" : "my-uuid",
         "email" : "me@email.com",
         "custom" : {
            "foo" : "bar"
         },
         "externalId" : null,
         "eTag" : "AePWsMnEl9m23wE",
         "profileUrl" : null
      }
   ],
   "next" : "Mg",
}
```

#### Other examples

Get the next page of the results.

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllUUIDMetadata({
        limit: 1,
        include: {
            customFields: true,
        },
        page: {
            next: "Mg", // from previous response
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched uuid metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch uuid metadata');
    });
};
```

#### Response

```json
{
  "status": 200,
  "data": [
    {
      "created": "2020-03-10T18:45:49.460388Z",
      "eTag": "Ad+6yqHMr6TYxgE",
      "email": null,
      "externalId": null,
      "id": "my-other-uuid",
      "name": "my-other-name",
      "profileUrl": null,
      "updated": "2020-03-10T18:45:49.460388Z"
    }
  ],
  "next": "MQ",
  "prev": "Mg",
}
```

### Get user metadata

Returns metadata for the specified UUID, optionally including the custom data object for each.

#### Usage

```javascript
getUUIDMetadata({uuid, include})
```

| Parameter | Description |
| --- | --- |
| `uuid` *Type: StringDefault: N/A | Unique UUID identifier. |
| `include`Type: ObjectDefault: N/A | Specifies whether to include the UUID's custom data field. |
| `customFields`Type: BooleanDefault: `true` | Whether to fetch custom fields. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getUUIDMetadata({
      uuid: 'my-uuid',
      include: {
        customFields: false,
      },
    })
    .then((resp) => {
      console.log(resp);
      return event.ok('Fetched UUID metadata successfully.');
    })
    .catch((err) => {
      console.log(err);
      return event.abort('Failed to fetch UUID metadata');
    });
};
```

#### Response

```json
{
   "status" : 200,
   "data" : {
      "email" : "me@email.com",
      "profileUrl" : null,
      "externalId" : null,
      "updated" : "2020-07-16T21:10:38.770048Z",
      "name" : "my-name",
      "eTag" : "AePWsMnEl9m23wE",
      "id" : "my-uuid"
   }
}
```

### Set user metadata

Set metadata for a UUID in the database, optionally including the custom data object for each.

#### Usage

```javascript
setUUIDMetadata({ uuid, data, include })
```

| Parameter | Description |
| --- | --- |
| `uuid` *Type: StringDefault: N/A | Unique UUID identifier. |
| `data` *Type: ObjectDefault: N/A | Object with UUID metadata to set. |
| `name`Type: StringDefault: N/A | Display name for the UUID, maximum `200` characters. |
| `externalId`Type: StringDefault: N/A | UUID's identifier in an external system. |
| `profileUrl`Type: StringDefault: N/A | The URL of the UUID's profile picture. |
| `email`Type: StringDefault: N/A | The UUID's email address, maximum `80` characters. |
| `custom`Type: ObjectDefault: N/A | JSON object of key-value pairs with supported data types. Values must be scalar only; arrays or objects are not supported. |
| `include`Type: ObjectDefault: N/A | Include additional fields in the response. |
| `customFields`Type: BooleanDefault: `true` | Whether to fetch custom fields. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setUUIDMetadata({
        uuid: 'my-uuid',
        data: {
            name: 'my-name',
            email: 'me@email.com',
            custom: {
                foo: 'bar',
            },
        },
        include: {
            customFields: false,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set UUID metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set UUID metadata.');
    });
};
```

#### Response

```json
{
  "status" : 200,
  "data" : {
    "email" : "me@email.com",
    "profileUrl" : null,
    "externalId" : null,
    "updated" : "2020-07-16T21:10:38.770048Z",
    "name" : "my-name",
    "eTag" : "AePWsMnEl9m23wE",
    "id" : "my-uuid"
  }
}
```

### Remove user metadata

Removes the metadata from a specified UUID.

#### Usage

```javascript
removeUUIDMetadata({ uuid })
```

| Parameter | Description |
| --- | --- |
| `uuid` *Type: String | Unique UUID identifier. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeUUIDMetadata({
        uuid: 'my-uuid',
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed UUID successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove UUID metadata');
    });
};
```

#### Response

```json
{
  "status": 200,
  "data": null
}
```

### Get metadata for all channels

Returns a paginated list of channel metadata objects, optionally including the custom data object for each.

#### Usage

```javascript
getAllChannelMetadata({include, filter, sort, limit, page})
```

| Parameter | Description |
| --- | --- |
| `include`Type: ObjectDefault: N/A | Include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllChannelMetadata({
        limit: 1,
        include: {
            totalCount: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch channel metadata');
    });
};
```

#### Response

```json
{
   "status" : 200,
   "data" : [
      {
         "name" : "channel-name",
         "description" : "What a great channel",
         "updated" : "2020-07-16T21:18:12.156794Z",
         "eTag" : "AeWFs+b3rMH4Dw",
         "id" : "my-channel"
      }
   ],
   "totalCount" : 2,
   "next" : "MQ"
}
```

#### Other examples

Get the next page of the results.

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getAllChannelMetadata({
        limit: 1,
        page: {
            next: "MQ", // from previous response
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch channel metadata');
    });
};
```

#### Response

```json
{
  "status" : 200,
  "data" : [
    {
      "updated" : "2020-07-16T21:19:28.735177Z",
      "eTag" : "AeDH5/ixi/7lZw",
      "id" : "my-other-channel",
      "description" : "What another great channel",
      "name" : "other-channel-name"
    }
  ],
  "prev" : "MQ",
  "next" : "Mg"
}
```

### Get channel metadata

Returns metadata for the specified channel, optionally including the custom data object for each.

#### Usage

```javascript
getChannelMetadata({channel, include})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | Unique channel identifier. |
| `include`Type: ObjectDefault: N/A | Specifies whether to include the channel's custom data field. |
| `customFields`Type: BooleanDefault: `true` | Whether to fetch custom fields. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getChannelMetadata({
        channel: 'my-channel',
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch channel metadata');
    });
};
```

#### Response

```json
{
  "status" : 200,
  "data" : {
    "description" : "What a great channel",
    "eTag" : "AeWFs+b3rMH4Dw",
    "id" : "my-channel",
    "updated" : "2020-07-16T21:18:12.156794Z",
    "custom" : {
       "foo" : "bar"
    },
    "name" : "channel-name"
  }
}
```

### Set channel metadata

Set metadata for a channel in the database, optionally including the custom data object for each.

#### Usage

```javascript
setChannelMetadata({ channel, data, include })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | Unique channel identifier. |
| `data` *Type: ObjectDefault: N/A | Object with channel metadata to set. |
| `name`Type: StringDefault: N/A | Name of the channel. |
| `description`Type: StringDefault: N/A | Description of the channel. |
| `custom`Type: ObjectDefault: N/A | JSON object of key-value pairs with supported data types. Values must be scalar only; arrays or objects are not supported. |
| `include`Type: ObjectDefault: N/A | Include additional fields in the response. |
| `customFields`Type: BooleanDefault: `true` | Whether to fetch custom fields. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setChannelMetadata({
        channel: 'my-channel',
        data: {
            name: 'channel-name',
            description: 'What a great channel',
            custom: {
                foo: 'bar',
            },
        },
        include: {
            customFields: false,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set channel metadata successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set channel metadata.');
    });
};
```

#### Response

```json
{
  "status" : 200,
  "data" : {
    "eTag" : "AeWFs+b3rMH4Dw",
    "id" : "my-channel",
    "name" : "channel-name",
    "description" : "What a great channel",
    "updated" : "2020-07-16T21:18:12.156794Z"
  }
}
```

### Remove channel metadata

Removes the metadata from a specified channel.

#### Usage

```javascript
removeChannelMetadata({ channel })
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | Unique channel identifier. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeChannelMetadata({
        channel: 'my-channel',
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed channel successfully');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove channel metadata');
    });
};
```

#### Response

```json
{
  "data": null,
  "status": 200
}
```

### Get channel memberships

The method returns a list of channel memberships for a user. This method doesn't return user's subscriptions.

#### Usage

```javascript
getMemberships({uuid, include, limit, page, filter, sort})
```

| Parameter | Description |
| --- | --- |
| `uuid` *Type: StringDefault: N/A | UUID whose memberships you wish to retrieve. |
| `include`Type: ObjectDefault: N/A | Specifies whether to include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `channelFields`Type: BooleanDefault: `false` | Whether to include fields for channel metadata. |
| `customChannelFields`Type: BooleanDefault: `false` | Whether to include custom fields for channel metadata. |
| `statusField`Type: BooleanDefault: `false` | Whether to include the membership's `status` field in the response. |
| `typeField`Type: BooleanDefault: `false` | Whether to include the membership's `type` field in the response. |
| `channelStatusField`Type: BooleanDefault: `false` | Whether to include the nested `channel` object's `status` from channel metadata (`include=channel.status`; distinct from membership `statusField`). |
| `channelTypeField`Type: BooleanDefault: `false` | Whether to include the nested `channel` object's `type` from channel metadata (`include=channel.type`; distinct from membership `typeField`). |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getMemberships({
        uuid: "my-uuid",
        limit: 2,
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched uuid memberships successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch memberships');
    });
}
```

#### Response

```json
{
  "status" : 200,
  "data" : [
    {
      "updated" : "2020-07-16T21:28:58.702287Z",
      "channel" : {
        "id" : "my-channel"
      },
      "eTag" : "AY39mJKK//C0VA",
      "status" : "active",
      "type" : null
    },
    {
      "eTag" : "AY39mJKK//C0VA",
      "updated" : "2020-07-16T21:28:21.992673Z",
      "channel" : {
        "id" : "my-other-channel"
      },
      "status" : null,
      "type" : null
    }
  ],
  "next" : "Mg"
}
```

### Set channel memberships

Set channel memberships for a UUID.

#### Usage

```javascript
setMemberships({uuid, channels, include, limit, page, filter, sort})
```

| Parameter | Description |
| --- | --- |
| `uuid` *Type: StringDefault: N/A | UUID whose memberships you wish to set. |
| `channels` *Type: ArrayDefault: N/A | Array of channels to set membership. Array can contain strings (channel-name only) or objects (which can include custom data). |
| `include`Type: ObjectDefault: N/A | Specifies whether to include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `channelFields`Type: BooleanDefault: `false` | Whether to include fields for channel metadata. |
| `customChannelFields`Type: BooleanDefault: `false` | Whether to include custom fields for channel metadata. |
| `statusField`Type: BooleanDefault: `false` | Whether to include the membership's `status` field in the response. |
| `typeField`Type: BooleanDefault: `false` | Whether to include the membership's `type` field in the response. |
| `channelStatusField`Type: BooleanDefault: `false` | Whether to include the nested `channel` object's `status` from channel metadata (`include=channel.status`; distinct from membership `statusField`). |
| `channelTypeField`Type: BooleanDefault: `false` | Whether to include the nested `channel` object's `type` from channel metadata (`include=channel.type`; distinct from membership `typeField`). |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by, and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setMemberships({
        uuid: "my-uuid",
        channels: [
            "my-channel",
            { id: "my-other-channel", custom: { hello: "world" } },
        ],
        include: {
            channelFields: true,
            customChannelFields: true,
            customFields: true,
            totalCount: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set uuid memberships successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set memberships');
    });
}
```

#### Response

```json
{
  "status" : 200,
  "data" : [
    {
      "channel" : {
        "id" : "my-channel"
      },
      "eTag" : "AY39mJKK//C0VA",
      "custom" : null,
      "updated" : "2020-07-16T21:28:58.702287Z",
      "status" : null,
      "type" : null
    },
    {
      "updated" : "2020-07-16T21:28:58.693461Z",
      "custom" : {
        "hello" : "world"
      },
      "channel" : {
        "updated" : "2020-07-16T21:19:28.735177Z",
        "name" : "other-channel-name",
        "custom" : {
          "foo" : "bar"
        },
        "eTag" : "AeDH5/ixi/7lZw",
        "id" : "my-other-channel",
        "description" : "What another great channel",
        "status" : null,
        "type" : "default"
      },
      "eTag" : "AbGV6rSh8LS/eg",
      "status" : null,
      "type" : null
    }
  ],
  "next" : "NA",
  "totalCount" : 2
}
```

### Remove channel memberships

Remove channel memberships for a UUID.

#### Usage

```javascript
removeMemberships({uuid, channels, include, limit, page, filter, sort})
```

| Parameter | Description |
| --- | --- |
| `uuid` *Type: StringDefault: N/A | UUID from which to remove memberships. |
| `channels` *Type: ArrayDefault: N/A | Array of channels to remove from uuid memberships. |
| `include`Type: ObjectDefault: N/A | Specifies whether to include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `channelFields`Type: BooleanDefault: `false` | Whether to include fields for channel metadata. |
| `customChannelFields`Type: BooleanDefault: `false` | Whether to include custom fields for channel metadata. |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by, and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeMemberships({
        uuid: "my-uuid",
        channels: [ "my-channel", "my-other-channel" ],
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed uuid memberships successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove memberships');
    });
}
```

#### Response

```json
{
  "status": 200,
  "data": []
}
```

### Get channel members

The method returns a list of members in a channel. The list will include user metadata for members that have additional metadata stored in the database.

#### Usage

```javascript
getChannelMembers({channel, include, limit, page, filter, sort})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | Channel for which to retrieve members. |
| `include`Type: ObjectDefault: N/A | Specifies whether to include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `UUIDFields`Type: BooleanDefault: `false` | Whether to include fields for uuid metadata. |
| `customUUIDFields`Type: BooleanDefault: `false` | Whether to include custom fields for uuid metadata. |
| `statusField`Type: BooleanDefault: `false` | Whether to include the member's `status` field in the response. |
| `typeField`Type: BooleanDefault: `false` | Whether to include the member's `type` field in the response. |
| `UUIDStatusField`Type: BooleanDefault: `false` | Whether to include the nested `uuid` object's `status` from UUID metadata (`include=uuid.status`; distinct from membership `statusField`). |
| `UUIDTypeField`Type: BooleanDefault: `false` | Whether to include the nested `uuid` object's `type` from UUID metadata (`include=uuid.type`; distinct from membership `typeField`). |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by, and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.getChannelMembers({
        channel: "my-channel",
        include: {
            UUIDFields: true,
        },
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Fetched channel members successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to fetch members');
    });
}
```

#### Response

```json
{
  "status" : 200,
  "next" : "Mg",
  "data" : [
    {
      "eTag" : "AbGV6rSh8LS/eg",
      "uuid" : {
        "id" : "my-other-uuid"
      },
      "updated" : "2020-07-16T21:40:48.367305Z",
      "status" : null,
      "type" : null
    },
    {
      "eTag" : "AY39mJKK//C0VA",
      "uuid" : {
        "profileUrl" : null,
        "eTag" : "AePWsMnEl9m23wE",
        "externalId" : null,
        "name" : "my-name",
        "id" : "my-uuid",
        "email" : "me@email.com",
        "updated" : "2020-07-16T21:44:27.504433Z",
        "status" : "active",
        "type" : "admin"
      },
      "updated" : "2020-07-16T21:40:48.357234Z",
      "status" : null,
      "type" : null
    }
  ]
}
```

### Set channel members

This method sets members in a channel.

#### Usage

```javascript
setChannelMembers({channel, uuids, include, limit, page, filter, sort})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | Channel for which to set members. |
| `uuids` *Type: ArrayDefault: N/A | Array of UUIDs to set as members. Array can contain strings (uuid-name only) or objects (which can include custom data). |
| `include`Type: ObjectDefault: N/A | Specifies whether to include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `UUIDFields`Type: BooleanDefault: `false` | Whether to include fields for uuid metadata. |
| `customUUIDFields`Type: BooleanDefault: `false` | Whether to include custom fields for uuid metadata. |
| `statusField`Type: BooleanDefault: `false` | Whether to include the member's `status` field in the response. |
| `typeField`Type: BooleanDefault: `false` | Whether to include the member's `type` field in the response. |
| `UUIDStatusField`Type: BooleanDefault: `false` | Whether to include the nested `uuid` object's `status` from UUID metadata (`include=uuid.status`; distinct from membership `statusField`). |
| `UUIDTypeField`Type: BooleanDefault: `false` | Whether to include the nested `uuid` object's `type` from UUID metadata (`include=uuid.type`; distinct from membership `typeField`). |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by, and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.setChannelMembers({
        channel: "my-channel",
        uuids: [
            "my-uuid",
            { id: "my-other-uuid", custom: { hello: "world" } },
        ],
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Set channel members successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to set members');
    });
}
```

#### Response

```json
{
  "status" : 200,
  "data" : [
    {
      "updated" : "2020-07-16T21:40:48.367305Z",
      "eTag" : "AbGV6rSh8LS/eg",
      "uuid" : {
        "id" : "my-other-uuid"
      },
      "status" : null,
      "type" : null
    },
    {
      "uuid" : {
        "id" : "my-uuid"
      },
      "eTag" : "AY39mJKK//C0VA",
      "updated" : "2020-07-16T21:40:48.357234Z",
      "status" : null,
      "type" : null
    }
  ],
  "next" : "Mg"
}
```

### Remove channel members

Remove members from a channel. The `include` object accepts the same fields as [Set channel members](#set-channel-members) in this document.

#### Usage

```javascript
removeChannelMembers({channel, uuids, include, limit, page, filter, sort})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: StringDefault: N/A | Channel from which to remove members. |
| `uuids` *Type: ArrayDefault: N/A | Array of UUIDs to remove from channel members. |
| `include`Type: ObjectDefault: N/A | Specifies whether to include additional fields in the response. |
| `customFields`Type: BooleanDefault: `false` | Whether to fetch custom fields. |
| `statusField`Type: BooleanDefault: `false` | Whether to include the member's `status` field in the response. |
| `typeField`Type: BooleanDefault: `false` | Whether to include the member's `type` field in the response. |
| `UUIDFields`Type: BooleanDefault: `false` | Whether to include fields for uuid metadata. |
| `customUUIDFields`Type: BooleanDefault: `false` | Whether to include custom fields for uuid metadata. |
| `UUIDStatusField`Type: BooleanDefault: `false` | Whether to include the nested `uuid` object's `status` from UUID metadata (`include=uuid.status`; distinct from membership `statusField`). |
| `UUIDTypeField`Type: BooleanDefault: `false` | Whether to include the nested `uuid` object's `type` from UUID metadata (`include=uuid.type`; distinct from membership `typeField`). |
| `totalCount`Type: BooleanDefault: `false` | Whether to include `totalCount` in response. |
| `limit`Type: NumberDefault: `100` | Maximum number of results to return per page. |
| `page`Type: ObjectDefault: N/A | Use for pagination. |
| `next`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination. It fetches the next page, allowing you to continue from where you left off. |
| `prev`Type: StringDefault: N/A | Random string returned from the server, indicating a specific position in a data set. Used for backward pagination. It fetches the previous page, enabling access to earlier data. Ignored if the `next` parameter is supplied. |
| `filter`Type: StringDefault: N/A | Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/general/metadata/filtering). |
| `sort`Type: ObjectDefault: N/A | Key-value pair of a property to sort by, and a sort direction. Available options are `id`, `name`, and `updated`. Sort directions are `asc` (ascending), `desc` (descending). For example, `{ name: 'asc' }`. |

```javascript
export default (event) => {
    const pubnub = require('pubnub');

    return pubnub.objects.removeChannelMembers({
        channel: "my-channel",
        uuids: [ "my-uuid", "my-other-uuid" ],
    })
    .then((resp) => {
        console.log(resp);
        return event.ok('Removed channel members successfully.');
    })
    .catch((error) => {
        console.log(err);
        return event.abort('Failed to remove members');
    });
}
```

#### Response

```json
{
  "status": 200,
  "data": []
}
```

## Message Reactions

### Add Message Reaction

Add an action on a published `message`.

#### Usage

```javascript
addMessageAction({channel, messageTimetoken, action:{type, value}, uuid})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Name of a channel which stores the message for which an action should be added. |
| `messageTimetoken` *Type: String | Timetoken of message for which action should be added. |
| `action` *Type: Hash | Message reaction information. |
| `action.type` *Type: String | What feature this message reaction represents. |
| `action.value` *Type: String | Value which should be stored along with a message reaction. |
| `uuid` *Type: String | The UUID associated with the reaction. |

```javascript
pubnub.addMessageAction({
    channel: 'channel1'
    messageTimetoken: '15610547826970040',
    action: {
        type: 'reaction',
        value: 'smiley_face',
    },
    uuid: 'uuid'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Remove Message Reaction

Remove a peviously added action on a published message.

#### Usage

```javascript
removeMessageAction({channel, messageTimetoken, actionTimetoken, uuid})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Name of a channel which stores the message for which an action should be removed. |
| `messageTimetoken` *Type: String | Timetoken of a message for which an action should be removed. |
| `actionTimetoken` *Type: String | Action addition timetoken. |
| `uuid` *Type: String | UUID associated with the action. |

```javascript
pubnub.removeMessageAction({
    channel: 'channel1'
    messageTimetoken: '15610547826970040',
    actionTimetoken: '15610547826970040',
    uuid: 'uuid'
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

### Get Message Reactions

Get a list of message reactions in a channel.

#### Usage

```javascript
getMessageActions({channel, start, end, limit})
```

| Parameter | Description |
| --- | --- |
| `channel` *Type: String | Name of a channel from which a list of messages actions should be retrieved. |
| `start`Type: String | Message reaction timetoken denoting the start of the range requested. Return values will be less than start. |
| `end`Type: String | Message reaction timetoken denoting the end of the range requested. Return values will be greater than or equal to end. |
| `limit`Type: Number | Number of message reactions to return in response. |

```javascript
pubnub.getMessageActions({
    channel: 'channel1',
    start: '15610547826970041',
    end: '15610547826970040',
    limit: 100,
}).then((response) => {
    console.log(response)
}).catch((error) => {
    // handle error
});
```

:::note Functions support
Functions provides a rich set of tools, and this documentation does not cover all of the potential situations you may encounter. If you need help with a situation not covered by the documentation, please contact [PubNub Support](https://www.pubnub.com/docs/mailto:support@pubnub.com)
:::

## Terms in this document

* **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.
