---
source_url: https://www.pubnub.com/docs/sdks/javascript/api-reference/file-sharing
title: File Sharing API for JavaScript SDK
updated_at: 2026-11-09T13:29:01.000Z
sdk_name: PubNub JavaScript SDK
sdk_version: 13.1.3
description: "Reference for the PubNub JavaScript SDK File Sharing methods: sendFile(), listFiles(), getFileUrl(), downloadFile(), deleteFile(), and publishFile(). Covers the FileInput types and the PubNub file object."
---

# File Sharing API 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

The PubNub JavaScript SDK uploads, lists, downloads, and deletes files on channels with [File Sharing](https://www.pubnub.com/docs/data-storage/files/overview.md), and `sendFile()` publishes a file message that announces each upload.

File Sharing must be enabled for the keyset in the [Admin Portal](https://admin.pubnub.com/). A file can be up to 5 MB. When Access Manager (v2/v3) is enabled, file operations need channel permissions. For how File Sharing works, retention, and permissions, see [Files](https://www.pubnub.com/docs/data-storage/files/overview.md).

Each method except getFileUrl() returns a promise that resolves with the response and rejects with a `PubNubError`. The error carries a `status` object with `category` and `statusCode`, and `status.errorData` holds the details that PubNub returned for a failed request. Each method except getFileUrl() also takes a callback as the second argument, and with a callback the method returns nothing and PubNub calls it with `(status, response)`. On success, `status.error` is `false` and `status.operation` names the operation, and on failure `status.error` is `true` and `response` is `null`. All examples use `async/await`, so wrap a call in `try...catch` to receive the error status.

`sendFile()` is the exception on failure: it calls the callback and also rejects its promise.

The methods take channel ID strings, not [SDK channel entities](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#sdk-entities).

## Send file

`sendFile()` uploads a file to a channel through a PubNub client for JavaScript, then publishes a file message that announces the upload.

`sendFile()` requests an upload URL from PubNub, uploads the file to the storage service, and publishes the file message with the file ID and name. For the publish step, see [Publish file message](#publish-file-message).

* Subscribers to the channel receive a file event with the file ID, the file name, and the optional message that came with the upload.
* To encrypt files, configure a [`cryptoModule`](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration.md#cryptomodule) during initialization. In Node.js and in browsers, `sendFile()` encrypts the file content with it. React Native does not encrypt file content. With `cryptoModule` configured, the SDK also encrypts the file message, which holds `message`, the file ID, and the file name. The SDK sends `channel` and `meta` unencrypted.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | string | Yes | n/a | ID of the channel to upload the file to. The method takes the ID string, not an [SDK channel entity](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#sdk-entities). The SDK rejects an empty value with `channel can't be empty`. |
| file | FileInput | Yes | n/a | File to upload. The accepted forms depend on the environment. |
| message | any | Optional | n/a | Message that travels with the file, such as a caption. Subscribers receive it in the file event. The SDK omits a falsy value. |
| storeInHistory | boolean | Optional | `true` | Whether PubNub stores the file message in [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md). `true` stores it and `false` skips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sends `true`, so the Message Persistence setting of the keyset does not decide. |
| ttl | number | Optional | n/a | The number of hours that Message Persistence keeps the file message. When omitted, the retention of the keyset applies. PubNub ignores this value when it does not store the message. The SDK omits the value `0`, so the retention of the keyset applies. |
| meta | any | Optional | n/a | Metadata that PubNub attaches to the file message. Subscribers can use it in [message filters](https://www.pubnub.com/docs/pub-sub/subscribe/filter-received-messages.md). The SDK sends `meta` only when it is an object or an array. |
| customMessageType | string | Optional | n/a | A business-specific label for the message, for example `text`, `action`, or `poll`. |

A custom message type accepted by the PubNub Publish, Signal, and File Sharing APIs must be a case-sensitive alphanumeric string of 3 to 50 characters. Dashes (`-`) and underscores (`_`) are allowed. The value cannot start with a special character or with the reserved prefixes `pn_` or `pn-`.

The deprecated `cipherKey` parameter is documented in [Deprecated cipherKey parameter](#deprecated-cipherkey-parameter).

### Returns

`sendFile()` resolves with a `SendFileResponse`. The `timetoken` is a string. The `id` and `name` identify the file that PubNub stores, and `name` is the name under which PubNub stores it.

#### Send file with push notification

:::tip Trigger push notifications when sharing files
To send mobile push notifications when sharing a file, include `pn_apns` (for iOS) and/or `pn_fcm` (for Android) payloads in the `message` parameter of the `sendFile` method.
When PubNub detects these reserved keys, it automatically forwards the push notification to the appropriate push service (APNs or FCM) for all devices registered on the channel.
:::

```javascript
// Create a notification payload with title and body
const notificationPayload = PubNub.notificationPayload('New File', 'A file was shared');

// Configure APNS2 with your specific topic and environment
notificationPayload.apns.configurations = [
{
  targets: [
    {
      topic: 'com.yourapp.bundleid',
      environment: 'production',
    },
  ],
},
];

// Build the payload for both APNS2 and FCM
const pushPayload = notificationPayload.buildPayload(['apns2', 'fcm']);

const fileMessage = {
...pushPayload,
text: 'Check out this file!',
};

await pubnub.sendFile({
channel: 'my-channel',
file: myFile,
message: fileMessage,
});
```

For more details on push notification payload structure, see the [iOS Push](https://www.pubnub.com/docs/integrations/mobile-push-notifications/send-push-notifications-ios.md) and [Android Push](https://www.pubnub.com/docs/integrations/mobile-push-notifications/send-push-notifications-android.md) documentation. To prevent the sender from receiving their own push notification, add their device token to `excluded_devices` in the `pn_push` targets.

### Send file errors

`sendFile()` rejects with a `PubNubError`, except when the SDK cannot build the file from `file`. Read `error.status.category` and `error.status.statusCode` to tell the cases apart.

| Condition | Result |
| --- | --- |
| The SDK cannot build the file from `file` | A plain `Error` with the message `Couldn't construct a file out of supplied options.` or `Couldn't guess filename out of the options. Please provide one.`, and no callback call. |
| `channel` is empty | `PNValidationErrorCategory`. The `status.message` value is `channel can't be empty`. |
| The upload to the storage service does not return HTTP `204` | A `PubNubError` whose `status.statusCode` is the HTTP status of the upload. The `status.errorData.message` value holds the reply of the storage service. |
| The publish step fails on every attempt | A `PubNubError` whose `status` holds the `channel`, `id`, and `name` of the uploaded file. By default, the SDK makes 5 attempts. Pass the three values to `publishFile()`. |

### Examples for Send file

#### Syntax

```typescript
pubnub.sendFile({
    channel: string,
    file: FileInput,
    message?: any,
    storeInHistory?: boolean,
    ttl?: number,
    meta?: any,
    customMessageType?: string
}): Promise<SendFileResponse>;
```

#### Basic usage

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

```javascript
// Function to send a file to a channel
// in node.js, make sure to import 'fs'
// and use the createReadStream method to read the file
const myFile = fs.createReadStream('./cat_picture.jpg');

const response = await pubnub.sendFile({
  channel: 'my_channel',
  file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'image/jpeg' },
  customMessageType: 'file-message',
});

console.log('File sent successfully:', response);
```

#### Returns

```typescript
type SendFileResponse = {
    status: number,
    timetoken: string,
    id: string,
    name: string
}
```

## List channel files

`listFiles()` returns the files that File Sharing stores for a channel, using a PubNub client for JavaScript.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | string | Yes | n/a | ID of the channel to list the files of. The method takes the ID string, not an [SDK channel entity](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#sdk-entities). The SDK rejects an empty value with `channel can't be empty`. |
| limit | number | Optional | `100` | Number of files to return in one call. A single list-files call returns up to 100 files for a channel. |
| next | string | Optional | n/a | Token from the `next` value of the previous response, which continues the list where that response ended. |

### Returns

`listFiles()` resolves with a `ListFilesResponse`. The `data` array holds one entry per file, and `created` is an ISO 8601 time string. The `count` value is the number of files in the response, and `next` is the token for the next page.

### Examples for List channel files

#### Syntax

```typescript
pubnub.listFiles({
    channel: string,
    limit?: number,
    next?: string
}): Promise<ListFilesResponse>;
```

#### Basic usage

```javascript
const response = await pubnub.listFiles({ channel: 'my_channel' });
console.log('Files listed successfully:', response);
```

#### Returns

```typescript
type ListFilesResponse = {
    status: number,
    data: Array<{
        name: string,
        id: string,
        size: number,
        created: string
    }>,
    next: string,
    count: number
}
```

## Get file URL

`getFileUrl()` builds the download URL of a file on a channel for a PubNub client for JavaScript, and sends no request to PubNub.

`getFileUrl()` returns the URL as a string and takes no callback. The method does not validate its parameters. The URL points to the file as PubNub stores it, so a file that the sender encrypted stays encrypted. The URL carries the query parameters that the SDK adds to every request, such as `pnsdk`, `uuid`, and `auth`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | string | Yes | n/a | ID of the channel that holds the file. The method takes the ID string, not an [SDK channel entity](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#sdk-entities). |
| id | string | Yes | n/a | ID of the file to build the URL for, which PubNub assigned at upload. |
| name | string | Yes | n/a | Name of the file to build the URL for, as PubNub stores it. |

### Returns

`getFileUrl()` returns the download URL as a string. The `auth` parameter appears only when the client has an authentication key or token.

### Examples for Get file URL

#### Syntax

```typescript
pubnub.getFileUrl({
    channel: string,
    id: string,
    name: string
}): string;
```

#### Basic usage

```javascript
const response = pubnub.getFileUrl({ channel: 'my_channel', id: '...', name: 'cat_picture.jpg' });
```

#### Returns

```javascript
'https://ps.pndsn.com/v1/files/demo/channels/my_channel/files/12345678-1234-5678-123456789012/cat_picture.jpg?pnsdk=PubNub-JS-Web%2F13.1.2&uuid=myUniqueUserId'
```

## Download file

`downloadFile()` downloads a file from a channel through a PubNub client for JavaScript.

`downloadFile()` resolves with a `PubNubFile` instance. Convert it with the methods of [PubNub file](#pubnub-file) for your environment. With a [`cryptoModule`](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration.md#cryptomodule) configured, the SDK decrypts the file content in Node.js and in browsers. React Native does not decrypt file content.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | string | Yes | n/a | ID of the channel to download the file from. The method takes the ID string, not an [SDK channel entity](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#sdk-entities). The SDK rejects an empty value with `channel can't be empty`. |
| id | string | Yes | n/a | ID of the file to download, which PubNub assigned at upload. The SDK rejects an empty value with `file id can't be empty`. |
| name | string | Yes | n/a | Name of the file to download, as PubNub stores it. The SDK rejects an empty value with `file name can't be empty`. |

The deprecated `cipherKey` parameter is documented in [Deprecated cipherKey parameter](#deprecated-cipherkey-parameter).

### Sample code

Choose the sample for your environment.

### Returns

`downloadFile()` resolves with a `PubNubFile`. In React Native, the file reads its content from an `ArrayBuffer`, so `toBlob()` and `toFile()` reject. Use `toArrayBuffer()` or `toString()` there.

### Examples for Download file

#### Syntax

```typescript
pubnub.downloadFile({
    channel: string,
    id: string,
    name: string
}): Promise<PubNubFile>;
```

#### Basic usage (Node.js)

```javascript
// In Node.js using streams:
// import fs from 'fs'
const downloadFileResponse = await pubnub.downloadFile({
  channel: 'my_channel',
  id: '...',
  name: 'cat_picture.jpg',
});

const output = fs.createWriteStream('./cat_picture.jpg');
const fileStream = await downloadFileResponse.toStream();

fileStream.pipe(output);

output.once('finish', () => {
  console.log('File saved to ./cat_picture.jpg');
});
```

#### Basic usage (Browser)

```javascript
// In browser
// download the intended file
const downloadFile = async () => {
  const file = await pubnub.downloadFile({
    channel: 'my_channel',
    id: '...',
    name: 'cat_picture.jpg',
  });

  // have proper html element to display the file
  const myImageTag = document.createElement('img');
  myImageTag.src = URL.createObjectURL(await file!.toFile());

  // attach the file content to the html element
  document.body.appendChild(myImageTag);
};
```

#### Basic usage (React and React Native)

```javascript
// in React and React Native
const file = await pubnub.downloadFile({
  channel: 'awesomeChannel',
  id: 'imageId',
  name: 'cat_picture.jpg',
});

// toArrayBuffer() works in React and React Native (toBlob() is not supported in React Native)
const fileContent = await file.toArrayBuffer();
```

## Delete file

`deleteFile()` deletes a file from a channel through a PubNub client for JavaScript.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | string | Yes | n/a | ID of the channel to delete the file from. The method takes the ID string, not an [SDK channel entity](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#sdk-entities). The SDK rejects an empty value with `channel can't be empty`. |
| id | string | Yes | n/a | ID of the file to delete, which PubNub assigned at upload. The SDK rejects an empty value with `file id can't be empty`. |
| name | string | Yes | n/a | Name of the file to delete, as PubNub stores it. The SDK rejects an empty value with `file name can't be empty`. |

### Returns

`deleteFile()` resolves with a `DeleteFileResponse`. A successful deletion returns the status `200`.

### Examples for Delete file

#### Syntax

```typescript
pubnub.deleteFile({
    channel: string,
    id: string,
    name: string
}): Promise<DeleteFileResponse>;
```

#### Basic usage

```javascript
const deleteFileResponse = await pubnub.deleteFile({
  channel: 'my_channel',
  id: '...',
  name: 'cat_picture.jpg',
});
console.log('File deleted successfully:', deleteFileResponse);
```

#### Returns

```typescript
type DeleteFileResponse = {
    status: number
}
```

## Publish file message

`publishFile()` publishes a file message for a file that PubNub already stores, using a PubNub client for JavaScript.

The file message carries the file ID and the file name, which together identify the file for download. Call `publishFile()` when the upload succeeded but the publish step of `sendFile()` failed, to publish the file message without uploading the file again. When `sendFile()` rejects because the publish step failed, read `channel`, `id`, and `name` from `error.status` and pass them as `channel`, `fileId`, and `fileName`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channel | string | Yes | n/a | ID of the channel to publish the file message to. The method takes the ID string, not an [SDK channel entity](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#sdk-entities). The SDK rejects an empty value with `channel can't be empty`. |
| fileId | string | Yes | n/a | ID of the uploaded file, which PubNub assigned at upload. The SDK rejects an empty value with `file id can't be empty`. |
| fileName | string | Yes | n/a | Name of the uploaded file, as PubNub stores it. The SDK rejects an empty value with `file name can't be empty`. |
| message | any | Optional | n/a | Message to publish with the file. Subscribers receive it in the file event. The SDK omits a falsy value. |
| storeInHistory | boolean | Optional | `true` | Whether PubNub stores the file message in [Message Persistence](https://www.pubnub.com/docs/data-storage/message-history/overview.md). `true` stores it and `false` skips storage. PubNub stores the message only when Message Persistence is enabled for the keyset. When omitted, the SDK sends `true`, so the Message Persistence setting of the keyset does not decide. |
| ttl | number | Optional | n/a | The number of hours that Message Persistence keeps the file message. When omitted, the retention of the keyset applies. PubNub ignores this value when it does not store the message. The SDK omits the value `0`, so the retention of the keyset applies. |
| meta | any | Optional | n/a | Metadata that PubNub attaches to the file message. Subscribers can use it in [message filters](https://www.pubnub.com/docs/pub-sub/subscribe/filter-received-messages.md). The SDK sends `meta` only when it is an object or an array. |
| customMessageType | string | Optional | n/a | A business-specific label for the file message, for example `text`, `action`, or `poll`. The accepted format is the same as for `sendFile()`. See [Send file](#send-file). |

### Returns

`publishFile()` resolves with a `PublishFileMessageResponse`. The `timetoken` is a string.

### Examples for Publish file message

#### Syntax

```typescript
pubnub.publishFile({
    channel: string,
    fileId: string,
    fileName: string,
    message?: any,
    storeInHistory?: boolean,
    ttl?: number,
    meta?: any,
    customMessageType?: string
}): Promise<PublishFileMessageResponse>;
```

#### Basic usage

```javascript
const fileMessageResponse = await pubnub.publishFile({
  channel: 'my_channel',
  fileId: '...',
  fileName: 'cat_picture.jpg',
  message: { field: 'value' },
  customMessageType: 'file-message',
});
console.log('File message published successfully:', fileMessageResponse);
```

#### Returns

```typescript
type PublishFileMessageResponse = {
    timetoken: string
}
```

## FileInput

`FileInput` describes the values that the `file` parameter of `sendFile()` accepts in the PubNub JavaScript SDK. The accepted forms depend on the environment.

### Node.js

In Node.js, `mimeType` defaults to `application/octet-stream`. The `data` property accepts a `Buffer`, an `ArrayBuffer`, or a string. For a string, the optional `encoding` property sets the encoding and defaults to `utf8`.

### Browsers

In a browser, `file` accepts a `File` or an object whose `data` property is a string, an `ArrayBuffer`, an `ArrayBufferView`, or a `Blob`.

The `data` property also accepts a `Blob` or an `ArrayBufferView`.

### React and React Native

React in a browser accepts the forms of the browser. React Native accepts a `File`, an object with a `data` property like the one for browsers, and an object with a `uri` property.

### Examples for FileInput

#### Using streams

```javascript
{
    stream: Readable,
    name: string,
    mimeType?: string
}
```

#### Using buffers

```javascript
{
    data: Buffer,
    name: string,
    mimeType?: string
}
```

#### Using File API

```javascript
File
```

#### Using strings

```javascript
{
    data: string,
    name: string,
    mimeType?: string
}
```

#### Using ArrayBuffer

```javascript
{
    data: ArrayBuffer,
    name: string,
    mimeType?: string
}
```

#### Using URI

```javascript
{
    uri: string,
    name: string,
    mimeType?: string
}
```

## PubNub file

`PubNubFile` is the file object of the PubNub JavaScript SDK. `downloadFile()` resolves with it, and `sendFile()` builds it from `FileInput`. The methods that work depend on the environment, and a method that the environment does not support rejects.

### Methods supported in Node.js

In Node.js, `file.toBuffer()` resolves with a `Buffer`, `file.toStream()` resolves with a `Readable` stream, and `file.toArrayBuffer()` resolves with an `ArrayBuffer`. The method `file.toString(encoding?: string)` resolves with a string encoded with `encoding`, which defaults to `utf8`. The methods `toFile()`, `toBlob()`, and `toFileUri()` reject.

### Methods supported in a browser

In a browser, `file.toFile()` resolves with a `File`, `file.toBlob()` resolves with a `Blob`, and `file.toArrayBuffer()` resolves with an `ArrayBuffer`. The method `file.toString()` resolves with a string that holds the binary content of the file and takes no `encoding` argument. The methods `toBuffer()`, `toStream()`, and `toFileUri()` reject.

### Methods supported in React Native

In React Native, `file.toArrayBuffer()` resolves with an `ArrayBuffer`, and `file.toString()` resolves with a string and takes no `encoding` argument. For a file that you created from a `File`, `file.toBlob()` and `file.toFile()` resolve with that `File`. For a file that you created from a string or a `Blob`, they resolve with a `Blob`. Both reject for a file that you created from an `ArrayBuffer`, a typed array, or a `uri`, and for a file that `downloadFile()` returns, so use `toArrayBuffer()` there.

In React Native, `file.toFileUri()` resolves with the `{ uri, name, type }` object of a file that you created from a `uri` and rejects for any other file. The methods `toBuffer()` and `toStream()` reject.

## Deprecated cipherKey parameter

The `cipherKey` parameter of `sendFile()` and `downloadFile()` still works in the PubNub JavaScript SDK, and a crypto module replaces it.

The reference for apps that still pass `cipherKey`, with the replacement, is [File Sharing API: deprecated cipherKey parameter for JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript/api-reference/file-sharing-legacy.md). New apps configure a [`cryptoModule`](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration.md#cryptomodule).

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