### Install PubNub JavaScript SDK via npm Source: https://github.com/pubnub/javascript/blob/master/README.md Use this command to add the PubNub JavaScript SDK to your project when using npm. ```bash npm install pubnub ``` -------------------------------- ### Get Presence Information with State Source: https://context7.com/pubnub/javascript/llms.txt Use hereNow to get current subscriber information, including UUIDs and state, for specified channels and channel groups. Ensure PubNub is initialized with publish and subscribe keys. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Get presence information with state try { const response = await pubnub.hereNow({ channels: ['ch1'], channelGroups: ['cg1'], includeUUIDs: true, includeState: true, }); console.log('Here Now Result:', response); // Access total occupancy console.log('Total occupancy:', response.totalOccupancy); // Access per-channel data response.channels['ch1'].occupants.forEach((occupant) => { console.log('UUID:', occupant.uuid); console.log('State:', occupant.state); }); } catch (error) { console.error(`Here Now failed: ${error}.${(error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''}`); } ``` -------------------------------- ### Get User Memberships - PubNub JS Source: https://context7.com/pubnub/javascript/llms.txt Retrieve all channels a user is a member of, with options to include custom fields and channel details. The PubNub client must be initialized. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Get memberships for current user try { const response = await pubnub.objects.getMemberships({ include: { customFields: true, channelFields: true, }, }); console.log('My memberships:', response.totalCount); response.data.forEach((membership) => { console.log('Channel:', membership.channel.id, membership.channel.name); console.log('Custom:', membership.custom); }); } catch (error) { console.error(`Get memberships error: ${error}`); } ``` -------------------------------- ### Subscribe to Channels and Handle Events Source: https://context7.com/pubnub/javascript/llms.txt Subscribe to a channel to receive various event types like messages, presence, signals, and files. Configure specific listeners for each event type. Ensure to call subscribe() to start receiving events and dispose() when done. ```typescript import PubNub, { Subscription } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'YOUR_PUBLISH_KEY', subscribeKey: 'YOUR_SUBSCRIBE_KEY', userId: 'YOUR_USER_ID', }); // Create a channel entity and subscription const channel = pubnub.channel('my_channel'); const subscription = channel.subscription({ receivePresenceEvents: true, // to receive presence events }); // Event-specific listeners subscription.onMessage = (messageEvent) => { console.log('Message event:', messageEvent); console.log('Channel:', messageEvent.channel); console.log('Timetoken:', messageEvent.timetoken); console.log('Message:', messageEvent.message); console.log('Publisher:', messageEvent.publisher); }; subscription.onPresence = (presenceEvent) => { console.log('Presence event:', presenceEvent); console.log('Action:', presenceEvent.action); // join, leave, timeout, state-change console.log('Channel:', presenceEvent.channel); }; subscription.onSignal = (signalEvent) => { console.log('Signal event:', signalEvent); }; subscription.onFile = (fileEvent) => { console.log('File event:', fileEvent); console.log('File ID:', fileEvent.file.id); console.log('File name:', fileEvent.file.name); }; subscription.onMessageAction = (messageActionEvent) => { console.log('Message Action event:', messageActionEvent); }; subscription.onObjects = (objectsEvent) => { console.log('Objects event:', objectsEvent); }; // Subscribe to start receiving events subscription.subscribe(); // Unsubscribe when done subscription.unsubscribe(); // Clean up subscription subscription.dispose(); ``` -------------------------------- ### Get Presence for Channel Groups Source: https://context7.com/pubnub/javascript/llms.txt Use hereNow to fetch presence information for channel groups. This allows monitoring occupancy across a collection of related channels. ```typescript // For channel groups try { const response = await pubnub.hereNow({ channelGroups: ['my_channel_group'], }); console.log('Channel group hereNow:', response); } catch (error) { console.error('hereNow failed:', error); } ``` -------------------------------- ### Get All Channel Metadata (Paginated) - PubNub JS Source: https://context7.com/pubnub/javascript/llms.txt Fetch all channel metadata with pagination support. Useful for listing channels and their properties. Requires an initialized PubNub client. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Get all channel metadata (paginated) try { const response = await pubnub.objects.getAllChannelMetadata({ limit: 100, include: { customFields: true }, }); console.log('Total channels:', response.totalCount); response.data.forEach((channel) => { console.log('Channel:', channel.id, channel.name); }); } catch (error) { console.error(`Get all channels error: ${error}`); } ``` -------------------------------- ### Get Occupancy Only Source: https://context7.com/pubnub/javascript/llms.txt Retrieve only the occupancy count for a channel using hereNow by setting includeUUIDs to false. This is useful when detailed subscriber information is not required. ```typescript // Get occupancy only (without UUIDs) try { const response = await pubnub.hereNow({ channels: ['my_channel'], includeUUIDs: false, }); console.log('Channel occupancy:', response.totalOccupancy); } catch (error) { console.error('hereNow failed:', error); } ``` -------------------------------- ### Get Channel Members - PubNub JS Source: https://context7.com/pubnub/javascript/llms.txt Retrieve all members of a specific channel, with options to include custom fields and user details. The PubNub client must be initialized. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Get channel members try { const response = await pubnub.objects.getChannelMembers({ channel: 'channel-1', include: { customFields: true, UUIDFields: true, }, }); console.log('Channel members:', response.totalCount); response.data.forEach((member) => { console.log('Member:', member.uuid.id, member.uuid.name); }); } catch (error) { console.error(`Get members error: ${error}`); } ``` -------------------------------- ### Message Persistence Source: https://context7.com/pubnub/javascript/llms.txt Retrieve historical messages, delete messages by range, and get message counts for channels. ```APIDOC ## GET /fetchMessages ### Description Retrieve historical messages from channels with optional metadata and actions. ### Parameters #### Request Body - **channels** (array) - Required - List of channels - **count** (number) - Optional - Max messages per channel - **includeMeta** (boolean) - Optional - Include message metadata - **includeMessageActions** (boolean) - Optional - Include message actions ## DELETE /deleteMessages ### Description Delete specific messages by timetoken range. ### Parameters #### Request Body - **channel** (string) - Required - Channel name - **start** (string) - Required - Exclusive start timetoken - **end** (string) - Required - Inclusive end timetoken ## GET /messageCounts ### Description Get message counts since specific timetokens. ### Parameters #### Request Body - **channels** (array) - Required - List of channels - **channelTimetokens** (array) - Required - List of timetokens corresponding to channels ``` -------------------------------- ### Get Channel Metadata - PubNub JS Source: https://context7.com/pubnub/javascript/llms.txt Retrieve metadata for a specific channel, optionally including custom fields. The PubNub client must be initialized. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Get channel metadata try { const response = await pubnub.objects.getChannelMetadata({ channel: 'team.red', include: { customFields: true }, }); console.log('Channel info:', response.data); } catch (error) { console.error(`Get channel metadata error: ${error}`); } ``` -------------------------------- ### Get User State Source: https://context7.com/pubnub/javascript/llms.txt Retrieve the current state data for a specific user on given channels or channel groups using getState. This is useful for accessing presence-related information. ```typescript // Get user state try { const response = await pubnub.getState({ uuid: 'some-user-id', channels: ['ch1'], channelGroups: ['cg1'], }); console.log('State retrieved:', response.channels); } catch (error) { console.error(`State retrieval failed: ${error}`); } ``` -------------------------------- ### Delete Messages by Timetoken Range Source: https://context7.com/pubnub/javascript/llms.txt Remove messages from a channel within a specified start (exclusive) and end (inclusive) timetoken range using deleteMessages. This is useful for data cleanup. ```typescript // Delete specific messages by timetoken range try { const response = await pubnub.deleteMessages({ channel: 'ch1', start: '15526611838554310', // exclusive end: '15526611838554320', // inclusive }); console.log('Delete messages response:', response); } catch (error) { console.error(`Delete messages failed: ${error}`); } ``` -------------------------------- ### Get Message Counts Since Timetokens Source: https://context7.com/pubnub/javascript/llms.txt Obtain the number of messages in specified channels since particular timetokens using messageCounts. This function requires an array of channels and corresponding channel timetokens. ```typescript // Get message counts since specific timetokens try { const response = await pubnub.messageCounts({ channels: ['ch1', 'ch2', 'ch3'], channelTimetokens: [ '15526611838554310', // timetoken for ch1 '15526611838554311', // timetoken for ch2 '15526611838554312', // timetoken for ch3 ], }); console.log('Message counts:', response.channels); // Output: { ch1: 42, ch2: 15, ch3: 8 } } catch (error) { console.error(`Message counts failed: ${error}`); } ``` -------------------------------- ### Configure PubNub Instance Source: https://github.com/pubnub/javascript/blob/master/README.md Instantiate the PubNub object with your publish and subscribe keys, and a unique user ID for authentication. ```javascript pubnub = new PubNub({ publishKey: 'myPublishKey', subscribeKey: 'mySubscribeKey', userId: 'myUniqueUserId', }); ``` -------------------------------- ### Send, List, Download, and Delete Files with PubNub JavaScript Source: https://context7.com/pubnub/javascript/llms.txt Demonstrates file sharing operations including sending files with optional encryption, listing files in a channel, downloading files, and deleting them. Ensure the file path is correct for `fs.readFileSync`. ```typescript import PubNub, { PubNubError } from 'pubnub'; import fs from 'fs'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Send a file (Node.js) try { const myFile = fs.readFileSync('./cat_picture.jpg'); const response = await pubnub.sendFile({ channel: 'my_channel', message: 'Look at this picture!', file: { data: myFile, name: 'cat_picture.jpg', mimeType: 'image/jpeg', }, cipherKey: 'myCipherKey', // optional encryption }); console.log('File sent:', response); console.log('File ID:', response.id); console.log('File name:', response.name); } catch (error) { console.error(`Error sending file: ${error}`); } // List files in a channel try { const response = await pubnub.listFiles({ channel: 'my_channel', limit: 100, }); console.log('Files in channel:'); response.data.forEach((file) => { console.log('File:', file.name, 'ID:', file.id); }); } catch (error) { console.error(`Error listing files: ${error}`); } // Download a file try { const file = await pubnub.downloadFile({ channel: 'my_channel', id: 'file-id', name: 'cat_picture.jpg', cipherKey: 'myCipherKey', // if encrypted }); // file contains the decrypted content console.log('File downloaded'); } catch (error) { console.error(`Error downloading file: ${error}`); } // Get file URL const fileUrl = pubnub.getFileUrl({ channel: 'my_channel', id: 'file-id', name: 'cat_picture.jpg', }); console.log('File URL:', fileUrl); // Delete a file try { const response = await pubnub.deleteFile({ channel: 'my_channel', id: 'file-id', name: 'cat_picture.jpg', }); console.log('File deleted:', response); } catch (error) { console.error(`Error deleting file: ${error}`); } ``` -------------------------------- ### Initialize PubNub Client Source: https://context7.com/pubnub/javascript/llms.txt Configure the PubNub client with essential keys and optional settings like encryption, logging, and authentication. Supports various environments including Node.js and browsers. ```typescript import PubNub from 'pubnub'; // Basic configuration for pub/sub operations const pubnub = new PubNub({ publishKey: 'myPublishKey', subscribeKey: 'mySubscribeKey', userId: 'myUniqueUserId', }); ``` ```typescript // Configuration with encryption enabled (recommended 256-bit AES-CBC) const pubnubEncrypted = new PubNub({ subscribeKey: 'mySubscribeKey', publishKey: 'myPublishKey', userId: 'myUniqueUserId', cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({ cipherKey: 'pubnubenigma' }), authKey: 'myAuthKey', logLevel: PubNub.LogLevel.Debug, ssl: true, }); ``` ```typescript // Server-side configuration with secret key const pubnubServer = new PubNub({ subscribeKey: 'mySubscribeKey', publishKey: 'myPublishKey', userId: 'myUniqueUserId', secretKey: 'secretKey', heartbeatInterval: 0, }); ``` ```typescript // Read-only client (subscribe only) const pubnubReadOnly = new PubNub({ subscribeKey: 'mySubscribeKey', userId: 'myUniqueUserId', }); ``` -------------------------------- ### Publish messages to a channel Source: https://github.com/pubnub/javascript/blob/master/README.md Demonstrates how to publish a message to a specific channel with optional configuration for history storage and metadata. ```javascript const channel = pubnub.channel('my_channel'); const subscription = channel.subscription(); subscription.subscribe(); try { const result = await pubnub.publish({ message: { such: "object", }, channel: "my_channel", sendByPost: false, // true to send via post storeInHistory: false, //override default Message Persistence options meta: { cool: "meta", }, // publish extra meta with the request }); } catch (status) { console.log(status); } ``` -------------------------------- ### Manage Channel Groups with TypeScript Source: https://context7.com/pubnub/javascript/llms.txt Organize channels into groups to enable subscribing to multiple channels with a single call. Groups support up to 2000 channels. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Add channels to a group try { const response = await pubnub.channelGroups.addChannels({ channels: ['ch1', 'ch2', 'ch3'], channelGroup: 'myChannelGroup', }); console.log('Channels added to group:', response); } catch (error) { console.error(`Add channels error: ${error}`); } // List channels in a group try { const response = await pubnub.channelGroups.listChannels({ channelGroup: 'myChannelGroup', }); console.log('Channels in group:'); response.channels.forEach((channel) => { console.log(' -', channel); }); } catch (error) { console.error(`List channels error: ${error}`); } // Remove channels from a group try { const response = await pubnub.channelGroups.removeChannels({ channels: ['ch1'], channelGroup: 'myChannelGroup', }); console.log('Channels removed from group:', response); } catch (error) { console.error(`Remove channels error: ${error}`); } // Delete an entire channel group try { const response = await pubnub.channelGroups.deleteGroup({ channelGroup: 'myChannelGroup', }); console.log('Channel group deleted:', response); } catch (error) { console.error(`Delete group error: ${error}`); } ``` -------------------------------- ### Presence - Where Now and State Source: https://context7.com/pubnub/javascript/llms.txt Find which channels a user is subscribed to and manage user state data across channels. ```APIDOC ## GET /whereNow ### Description Find which channels a user is subscribed to. ### Parameters #### Request Body - **uuid** (string) - Required - The user ID to query ## POST /setState ### Description Set user state data for presence. ### Parameters #### Request Body - **state** (object) - Required - Key-value pairs of state data - **channels** (array) - Optional - Channels to apply state - **channelGroups** (array) - Optional - Channel groups to apply state ## GET /getState ### Description Get user state data. ### Parameters #### Request Body - **uuid** (string) - Required - The user ID to query - **channels** (array) - Optional - Channels to retrieve state from - **channelGroups** (array) - Optional - Channel groups to retrieve state from ``` -------------------------------- ### Grant, Set, Parse, and Revoke Access Tokens with PubNub JavaScript Source: https://context7.com/pubnub/javascript/llms.txt Shows how to generate access tokens for fine-grained permissions using specific resources or regex patterns. Includes setting the token for authenticated requests, parsing its details, and revoking it. Requires a `secretKey` for token generation. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', secretKey: 'mySecretKey', // required for grant token }); // Grant token with specific resource permissions try { const token = await pubnub.grantToken({ ttl: 15, // minutes authorized_uuid: 'my-authorized-uuid', resources: { channels: { 'channel-a': { read: true }, 'channel-b': { read: true, write: true }, 'channel-c': { read: true, write: true, delete: true }, }, groups: { 'channel-group-b': { read: true }, }, uuids: { 'uuid-c': { get: true }, 'uuid-d': { get: true, update: true }, }, }, }); console.log('Token:', token); } catch (error) { console.error(`Grant token error: ${error}`); } // Grant token using regex patterns try { const token = await pubnub.grantToken({ ttl: 15, authorized_uuid: 'my-authorized-uuid', patterns: { channels: { '^channel-[A-Za-z0-9]$': { read: true }, }, groups: { '^group-.*$': { read: true }, }, uuids: { '^user-.*$': { get: true }, }, }, }); console.log('Pattern token:', token); } catch (error) { console.error(`Grant token error: ${error}`); } // Set token for authenticated requests pubnub.setToken(token); // Parse token to inspect permissions const parsedToken = pubnub.parseToken(token); console.log('Token details:', parsedToken); // Revoke token try { await pubnub.revokeToken(token); console.log('Token revoked'); } catch (error) { console.error(`Revoke token error: ${error}`); } ``` -------------------------------- ### Add event listeners for PubNub channels Source: https://github.com/pubnub/javascript/blob/master/README.md Configures event-specific and generic listeners to handle messages, presence, signals, objects, message actions, and file events. ```javascript // create a subscription from a channel entity const channel = pubnub.channel('my_channel'); const subscription = channel.subscription(); subscription.subscribe(); // Event-specific listeners subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); }; subscription.onPresence = (presenceEvent) => { console.log("Presence event: ", presenceEvent); }; subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); }; subscription.onPresence = (presenceEvent) => { console.log("Presence event: ", presenceEvent); }; subscription.onSignal = (signalEvent) => { console.log("Signal event: ", signalEvent); }; subscription.onObjects = (objectsEvent) => { console.log("Objects event: ", objectsEvent); }; subscription.onMessageAction = (messageActionEvent) => { console.log("Message Action event: ", messageActionEvent); }; subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); }; // Generic listeners subscription.addListener({ // Messages message: function (m) { const channelName = m.channel; // Channel on which the message was published const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists) const pubTT = m.timetoken; // Publish timetoken const msg = m.message; // Message payload const publisher = m.publisher; // Message publisher }, // Presence // requires a subscription with presence presence: function (p) { const action = p.action; // Can be join, leave, state-change, or timeout const channelName = p.channel; // Channel to which the message belongs const occupancy = p.occupancy; // Number of users subscribed to the channel const state = p.state; // User state const channelGroup = p.subscription; // Channel group or wildcard subscription match, if any const publishTime = p.timestamp; // Publish timetoken const timetoken = p.timetoken; // Current timetoken const uuid = p.uuid; // UUIDs of users who are subscribed to the channel }, // Signals signal: function (s) { const channelName = s.channel; // Channel to which the signal belongs const channelGroup = s.subscription; // Channel group or wildcard subscription match, if any const pubTT = s.timetoken; // Publish timetoken const msg = s.message; // Payload const publisher = s.publisher; // Message publisher }, // App Context objects: (objectEvent) => { const channel = objectEvent.channel; // Channel to which the event belongs const channelGroup = objectEvent.subscription; // Channel group const timetoken = objectEvent.timetoken; // Event timetoken const publisher = objectEvent.publisher; // UUID that made the call const event = objectEvent.event; // Name of the event that occurred const type = objectEvent.type; // Type of the event that occurred const data = objectEvent.data; // Data from the event that occurred }, // Message Reactions messageAction: function (ma) { const channelName = ma.channel; // Channel to which the message belongs const publisher = ma.publisher; // Message publisher const event = ma.event; // Message action added or removed const type = ma.data.type; // Message action type const value = ma.data.value; // Message action value const messageTimetoken = ma.data.messageTimetoken; // Timetoken of the original message const actionTimetoken = ma.data.actionTimetoken; // Timetoken of the message action }, // File Sharing file: function (event) { const channelName = event.channel; // Channel to which the file belongs const channelGroup = event.subscription; // Channel group or wildcard subscription match (if exists) const publisher = event.publisher; // File publisher const timetoken = event.timetoken; // Event timetoken const message = event.message; // Optional message attached to the file const fileId = event.file.id; // File unique id const fileName = event.file.name;// File name const fileUrl = event.file.url; // File direct URL } }); ``` -------------------------------- ### Publish Message with Persistence Source: https://context7.com/pubnub/javascript/llms.txt Publish a message and enable persistence in history for a specified duration (in hours). Options for sending via POST and including metadata are available. ```typescript // Publish with message persistence (store for 10 hours) try { const response = await pubnub.publish({ message: 'hello!', channel: 'my_channel', storeInHistory: true, ttl: 10, // hours customMessageType: 'text-message', sendByPost: false, // true to send via POST meta: { cool: 'meta' }, // publish extra metadata }); console.log('Message stored with server response:', response); } catch (error) { console.error(`Publish Failed: ${error}`); } ``` -------------------------------- ### Manage Multiple Subscriptions with Subscription Sets Source: https://context7.com/pubnub/javascript/llms.txt Combine multiple channel subscriptions into a single group for unified management and event handling. You can add and remove individual subscriptions or other subscription sets. ```typescript const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Create a subscription set with multiple channels const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'], subscriptionOptions: { receivePresenceEvents: true }, }); // Subscribe to the set subscriptionSet1.subscribe(); // Add another subscription set const subscriptionSet2 = pubnub.subscriptionSet({ channels: ['ch3', 'ch4'], }); subscriptionSet1.addSubscriptionSet(subscriptionSet2); // Create subscription from channel group and add it const channelGroup = pubnub.channelGroup('channelGroup_1'); const subscription2 = channelGroup.subscription(); subscriptionSet1.addSubscription(subscription2); // Now receiving events from ch1, ch2, ch3, ch4, and channelGroup_1 // Remove a subscription set from another subscription set subscriptionSet1.removeSubscriptionSet(subscriptionSet2); // Unsubscribe from the set subscriptionSet1.unsubscribe(); ``` -------------------------------- ### Presence - Here Now Source: https://context7.com/pubnub/javascript/llms.txt Retrieve information about currently subscribed users, including occupancy, UUIDs, and state data for specific channels or channel groups. ```APIDOC ## GET /hereNow ### Description Get information about currently subscribed users including occupancy, UUIDs, and their state data for channels or channel groups. ### Parameters #### Request Body - **channels** (array) - Optional - List of channels to query - **channelGroups** (array) - Optional - List of channel groups to query - **includeUUIDs** (boolean) - Optional - Whether to include list of UUIDs - **includeState** (boolean) - Optional - Whether to include state data ### Response #### Success Response (200) - **totalOccupancy** (number) - Total number of occupants - **channels** (object) - Map of channel data including occupants and state ``` -------------------------------- ### Listen for Connection Status Changes Source: https://context7.com/pubnub/javascript/llms.txt Implement listeners to monitor PubNub connection status, handling events like connection, disconnection, network issues, and successful reconnections. This is crucial for maintaining a robust real-time connection. ```typescript const pubnub = new PubNub({ publishKey: 'YOUR_PUBLISH_KEY', subscribeKey: 'YOUR_SUBSCRIBE_KEY', userId: 'YOUR_USER_ID', }); pubnub.addListener({ status: function (event) { if (event.category === 'PNConnectedCategory') { console.log('Connected to PubNub!'); console.log('Your user ID is:', pubnub.userId); } else if (event.category === 'PNNetworkIssuesCategory') { console.log('Connection lost'); // handle reconnection } else if (event.category === 'PNDisconnectedUnexpectedlyCategory') { console.log('Disconnected unexpectedly.'); } else if (event.category === 'PNReconnectedCategory') { console.log('Reconnected!'); } }, message: function (event) { console.log('New message:', event.message); }, presence: function (event) { console.log('Presence:', event.action, event.uuid); }, }); // Legacy subscribe syntax (still supported) pubnub.subscribe({ channels: ['my_channel_1', 'my_channel_2'], channelGroups: ['my_channelGroup'], withPresence: true, }); // Wildcard subscription pubnub.subscribe({ channels: ['ab.*'], }); // Unsubscribe from channels pubnub.unsubscribe({ channels: ['chan1', 'chan2'], channelGroups: ['demo_group1'], }); // Unsubscribe from all pubnub.unsubscribeAll(); ``` -------------------------------- ### App Context - User Metadata Source: https://context7.com/pubnub/javascript/llms.txt APIs for managing user (UUID) metadata, enabling the storage of user profiles and information that persists across sessions. ```APIDOC ## App Context - User Metadata ### Description Manage user (UUID) metadata for storing user profiles and information that persists across sessions. ### Method `PUT` (for setUUIDMetadata), `GET` (for getUUIDMetadata, getAllUUIDMetadata), `DELETE` (for removeUUIDMetadata) ### Endpoint `/v2/objects/users/{uuid}` (for setUUIDMetadata, getUUIDMetadata, removeUUIDMetadata) `/v2/objects/users` (for getAllUUIDMetadata) ### Parameters #### Path Parameters - **uuid** (string) - Required - The unique identifier for the user. #### Query Parameters - **include** (string) - Optional - Specifies fields to include in the response (e.g., `customFields`). - **limit** (integer) - Optional - For getAllUUIDMetadata, the maximum number of user metadata objects to return. - **filter** (string) - Optional - For getAllUUIDMetadata, a filter expression to apply to the results. - **sort** (string) - Optional - For getAllUUIDMetadata, a sort order for the results. #### Request Body (for setUUIDMetadata) - **data** (object) - Required - An object containing the user metadata. - **name** (string) - Optional - The user's name. - **email** (string) - Optional - The user's email address. - **profileUrl** (string) - Optional - The URL of the user's profile picture. - **custom** (object) - Optional - A key-value object for custom user fields. ### Request Example (setUUIDMetadata) ```json { "uuid": "user-123", "data": { "name": "John Doe", "email": "john@example.com", "profileUrl": "https://example.com/avatar.png", "custom": { "role": "admin", "department": "Engineering" } } } ``` ### Response #### Success Response (200) - **data** (object) - Contains the user metadata. - **id** (string) - The user's UUID. - **name** (string) - The user's name. - **email** (string) - The user's email address. - **profileUrl** (string) - The URL of the user's profile picture. - **custom** (object) - Custom user fields. - **updated** (string) - Timestamp of the last update. - **created** (string) - Timestamp of the creation. - **totalCount** (integer) - For getAllUUIDMetadata, the total number of user metadata objects. #### Response Example (setUUIDMetadata) ```json { "status": 200, "data": { "id": "user-123", "name": "John Doe", "email": "john@example.com", "profileUrl": "https://example.com/avatar.png", "custom": { "role": "admin", "department": "Engineering" }, "updated": "2023-10-27T10:00:00Z", "created": "2023-10-27T09:00:00Z" } } ``` #### Response Example (getAllUUIDMetadata) ```json { "status": 200, "totalCount": 2, "data": [ { "id": "user-123", "name": "John Doe", "created": "2023-10-27T09:00:00Z", "updated": "2023-10-27T10:00:00Z", "custom": { "role": "admin" } }, { "id": "user-456", "name": "Jane Smith", "created": "2023-10-27T09:05:00Z", "updated": "2023-10-27T09:05:00Z", "custom": { "role": "user" } } ] } ``` ``` -------------------------------- ### Set User Memberships - PubNub JS Source: https://context7.com/pubnub/javascript/llms.txt Assign channels to a user, optionally with custom data for each membership. Requires an initialized PubNub client. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Set memberships for a user try { const response = await pubnub.objects.setMemberships({ uuid: 'user-123', channels: [ { id: 'channel-1', custom: { role: 'owner' } }, { id: 'channel-2', custom: { role: 'member' } }, ], }); console.log('Memberships set:', response.data); } catch (error) { console.error(`Set memberships error: ${error}`); } ``` -------------------------------- ### Manage User Metadata with TypeScript Source: https://context7.com/pubnub/javascript/llms.txt Store and retrieve persistent user profile information using App Context. Metadata is associated with a UUID. ```typescript import PubNub, { PubNubError } from 'pubnub'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); // Set UUID metadata try { const response = await pubnub.objects.setUUIDMetadata({ uuid: 'user-123', // optional, defaults to current userId data: { name: 'John Doe', email: 'john@example.com', profileUrl: 'https://example.com/avatar.png', custom: { role: 'admin', department: 'Engineering', }, }, }); console.log('User metadata set:', response.data); } catch (error) { console.error(`Set metadata error: ${error}`); } // Get UUID metadata for current user try { const response = await pubnub.objects.getUUIDMetadata({ include: { customFields: true }, }); console.log('Current user metadata:', response.data); } catch (error) { console.error(`Get metadata error: ${error}`); } // Get all UUID metadata objects (paginated) try { const response = await pubnub.objects.getAllUUIDMetadata({ limit: 100, include: { customFields: true }, }); console.log('Total users:', response.totalCount); response.data.forEach((user) => { console.log('User:', user.id, user.name); }); } catch (error) { console.error(`Get all metadata error: ${error}`); } // Remove UUID metadata try { const response = await pubnub.objects.removeUUIDMetadata({ uuid: 'user-123', }); console.log('User metadata removed:', response); } catch (error) { console.error(`Remove metadata error: ${error}`); } ``` -------------------------------- ### Retrieve Server Time Source: https://context7.com/pubnub/javascript/llms.txt Fetches the current PubNub server time as a high-resolution timetoken for synchronization purposes. ```javascript const pubnub = new PubNub({ subscribeKey: 'demo', userId: 'myUniqueUserId', }); try { const response = await pubnub.time(); console.log('Server timetoken:', response.timetoken); // Convert timetoken to Date (timetoken is in 100ns units since Unix epoch) const date = new Date(parseInt(response.timetoken) / 10000); console.log('Server time:', date); } catch (error) { console.error('Time error:', error); } ``` -------------------------------- ### Message Actions (Reactions) Source: https://context7.com/pubnub/javascript/llms.txt APIs for adding, retrieving, and removing message actions such as reactions, receipts, and translations on published messages. ```APIDOC ## Message Actions (Reactions) ### Description Add, retrieve, and remove message actions (reactions, receipts, translations) on published messages. ### Method `POST` (for addMessageAction), `GET` (for getMessageActions), `DELETE` (for removeMessageAction) ### Endpoint `/v2/presence/sub_key/{subscribeKey}/message/actions ### Parameters #### Path Parameters - **subscribeKey** (string) - Required - Your PubNub subscribe key. #### Query Parameters - **channel** (string) - Required - The channel where the message action is associated. - **messageTimetoken** (string) - Required - The timetoken of the message to which the action is being added or removed. - **actionTimetoken** (string) - Required for removeMessageAction - The timetoken of the specific action to remove. - **start** (string) - Optional - The start timetoken for retrieving message actions. - **end** (string) - Optional - The end timetoken for retrieving message actions. - **limit** (integer) - Optional - The maximum number of message actions to retrieve. #### Request Body (for addMessageAction) - **action** (object) - Required - An object containing the type and value of the action. - **type** (string) - Required - The type of action (e.g., 'reaction', 'receipt', 'translation'). - **value** (string) - Required - The value of the action (e.g., 'smiley_face', 'read'). ### Request Example (addMessageAction) ```json { "channel": "channel_name", "messageTimetoken": "15610547826970040", "action": { "type": "reaction", "value": "smiley_face" } } ``` ### Response #### Success Response (200) - **data** (object) - Contains details about the added or removed action. - **actionTimetoken** (string) - The timetoken of the added or removed action. - **data** (array) - For getMessageActions, an array of action objects. - **type** (string) - The type of the message action. - **value** (string) - The value of the message action. - **uuid** (string) - The UUID of the user who performed the action. - **messageTimetoken** (string) - The timetoken of the message associated with the action. #### Response Example (addMessageAction) ```json { "status": 200, "data": { "actionTimetoken": "15610547826970045" } } ``` #### Response Example (getMessageActions) ```json { "status": 200, "data": [ { "type": "reaction", "value": "smiley_face", "uuid": "myUniqueUserId", "messageTimetoken": "15610547826970040" } ] } ``` ``` -------------------------------- ### Configure Retry Policies Source: https://context7.com/pubnub/javascript/llms.txt Sets up automatic retry strategies for failed requests, including exponential backoff, linear backoff, or disabling retries entirely. ```typescript import PubNub from 'pubnub'; // Exponential retry policy const pubnubWithExponential = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', retryConfiguration: PubNub.ExponentialRetryPolicy({ minimumDelay: 2, maximumDelay: 150, maximumRetry: 6, excludedEndpoints: [PubNub.Endpoint.Publish], // don't retry publish }), }); // Linear retry policy const pubnubWithLinear = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', retryConfiguration: PubNub.LinearRetryPolicy({ delay: 3, maximumRetry: 5, }), }); // Disable retry (use None policy) const pubnubNoRetry = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', retryConfiguration: PubNub.NoneRetryPolicy, }); ``` -------------------------------- ### File Sharing API Source: https://context7.com/pubnub/javascript/llms.txt APIs for uploading, downloading, listing, and deleting files with optional encryption. Files can be shared through channels. ```APIDOC ## File Sharing API ### Description APIs for uploading, downloading, listing, and deleting files with optional encryption. Files can be shared through channels. ### Endpoints #### Send File ##### Method POST ##### Endpoint `/publish` (internally handled by `pubnub.sendFile`) ##### Parameters - **channel** (string) - Required - The channel to send the file to. - **message** (string) - Optional - A message associated with the file. - **file** (object) - Required - File object containing `data`, `name`, and `mimeType`. - **data** (Buffer/Blob) - Required - The file content. - **name** (string) - Required - The name of the file. - **mimeType** (string) - Required - The MIME type of the file. - **cipherKey** (string) - Optional - Encryption key for the file. #### List Files ##### Method GET ##### Endpoint `/v2/presence/sub-key/{subKey}/channel/{channelName}/files/list` (internally handled by `pubnub.listFiles`) ##### Parameters - **channel** (string) - Required - The channel to list files from. - **limit** (number) - Optional - The maximum number of files to return. #### Download File ##### Method GET ##### Endpoint `/files/{subKey}/{channelName}/{fileId}/{fileName}/download` (internally handled by `pubnub.downloadFile`) ##### Parameters - **channel** (string) - Required - The channel the file belongs to. - **id** (string) - Required - The ID of the file to download. - **name** (string) - Required - The name of the file to download. - **cipherKey** (string) - Optional - Decryption key if the file was encrypted. #### Get File URL ##### Method GET ##### Endpoint `/files/{pubKey}/{channelName}/{fileId}/{fileName}/url` (internally handled by `pubnub.getFileUrl`) ##### Parameters - **channel** (string) - Required - The channel the file belongs to. - **id** (string) - Required - The ID of the file. - **name** (string) - Required - The name of the file. #### Delete File ##### Method DELETE ##### Endpoint `/files/{pubKey}/{channelName}/{fileId}/{fileName}` (internally handled by `pubnub.deleteFile`) ##### Parameters - **channel** (string) - Required - The channel the file belongs to. - **id** (string) - Required - The ID of the file to delete. - **name** (string) - Required - The name of the file to delete. ### Request Example (Send File) ```json { "channel": "my_channel", "message": "Look at this picture!", "file": { "data": "", "name": "cat_picture.jpg", "mimeType": "image/jpeg" }, "cipherKey": "myCipherKey" } ``` ### Response Example (Send File Success) ```json { "id": "file-id", "name": "cat_picture.jpg", "size": 102400, "type": "image/jpeg", "created": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Set User State for Presence Source: https://context7.com/pubnub/javascript/llms.txt Manage user state data across channels using setState. This allows associating custom information, like 'online' status or 'mood', with a user's presence. ```typescript // Set user state for presence try { const response = await pubnub.setState({ state: { status: 'online', mood: 'happy' }, channels: ['ch1'], channelGroups: ['cg1'], }); console.log('State set successfully:', response); } catch (error) { console.error(`State set failed: ${error}`); } ```