PubNub JavaScript SDK

repository·master·Indexed 20 days ago

https://github.com/pubnub/javascript

A high-performance real-time communication layer for sending and receiving data globally with low latency. Version 12.0.3 supports Node.js, React Native, and browser environments via npm or CDN. Key features include Publish/Subscribe messaging, the EventEngine for subscription lifecycle management, message history retrieval, presence tracking, and file sharing capabilities.

Tokens
18.1K
Snippets
54
Records
82
Agent score
69%

What's inside pubnub-javascript

  1. Add event listeners to a subscription

    master

    To receive real-time data, you must first create a channel and a subscription, then attach listeners. You can use two different patterns for listening to events:

    1. Event-specific property assignment

    You can assign callback functions directly to specific event properties on the subscription object (e.g., onMessage, onPresence, onSignal, onObjects, onMessageAction, onFile).

    2. Generic listener via addListener

    Use the addListener method to provide a single object containing multiple callback functions for different event types. This is useful for managing all event types in one place.

    Supported event types in addListener include:

    • message: Triggered when a message is received.
    • presence: Triggered on presence changes (requires a subscription with presence enabled).
    • signal: Triggered when a signal is received.
    • objects: Triggered by App Context events.
    • messageAction: Triggered by Message Reactions.
    • file: Triggered by File Sharing events.
    // create a subscription from a channel entity
    const channel = pubnub.channel('my_channel');
    const subscription = channel.subscription();
    subscription.subscribe();
    
    // Example: Event-specific listeners
    subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); };
    
    // Example: Generic listeners
    subscription.addListener({
      message: function (m) {
        const channelName = m.channel;
        const msg = m.message;
        // ...
      },
      presence: function (p) {
        const action = p.action; // join, leave, state-change, or timeout
        const occupancy = p.occupancy;
        // ...
      }
    });
  2. Install the PubNub JavaScript SDK

    master

    You can integrate the PubNub JavaScript SDK into your project using npm or by downloading a build from a CDN.

    Using npm

    npm install pubnub

    Using a CDN

    React Native Setup

    If you are using React Native, the SDK requires a global URL implementation. You must install react-native-url-polyfill as an optional peer dependency. The SDK will automatically load the polyfill once installed.

    npm install react-native-url-polyfill
  3. Configure the PubNub instance

    master

    To use the SDK, initialize a new PubNub instance with your credentials. You can obtain your publishKey and subscribeKey from the PubNub Admin Portal. It is also recommended to provide a unique userId.

    pubnub = new PubNub({
      publishKey: 'myPublishKey',
      subscribeKey: 'mySubscribeKey',
      userId: 'myUniqueUserId',
    });
  4. Configure reconnection and retry policies

    master

    You can customize how the SDK handles reconnections using the retryConfiguration option in the UserConfiguration object. This accepts a RequestRetryPolicy.

    Available policies include:

    • PubNub.LinearRetryPolicy({ delay, maximumRetry })
    • PubNub.ExponentialRetryPolicy({ minimumDelay, maximumDelay, maximumRetry })

    This allows you to control the timing and frequency of attempts to reconnect to PubNub services after network interruptions.

    const config: UserConfiguration = {
      subscribeKey: '...', 
      userId: '...',
      retryConfiguration: PubNub.ExponentialRetryPolicy({
        minimumDelay: 1000,
        maximumDelay: 30000,
        maximumRetry: 10
      })
    };
  5. Fetch message history from channels

    master

    Use the PubNub history feature to retrieve previously published messages from one or more channels. You can specify a time range using start and end timetokens and limit the number of messages returned with count.

    Key Constraints and Behaviors

    • Message Actions: If you set includeMessageActions: true, you can retrieve message reactions (actions). Note: This is only supported for a single channel. If you pass multiple channels while includeMessageActions is true, the request will fail validation.
    • Message Counts:
      • For a single channel (without actions), the default maximum is 100 messages.
      • For multiple channels or when requesting message actions, the default maximum is 25 messages.
    • Decryption: If you provided a crypto module during PubNub initialization, the SDK will automatically attempt to decrypt the message payloads returned by the history API.
    • File Messages: If a message is identified as a file message, the SDK uses the provided getFileUrl function to generate a downloadable URL for the file object within the message payload.
  6. Understand LogMessage types

    master

    When implementing a Logger, you will receive LogMessage objects. These are union types that provide different data structures depending on the messageType:

    • text: A simple string message (TextLogMessage).
    • object: A dictionary or array that should be serialized (ObjectLogMessage). Supports details and ignoredKeys for filtering sensitive data.
    • error: Contains a PubNubError object (ErrorLogMessage).
    • network-request: Contains a TransportRequest object, including canceled and failed flags (NetworkRequestLogMessage).
    • network-response: Contains a TransportResponse object (NetworkResponseLogMessage).

    All messages include a BaseLogMessage containing timestamp, pubNubId, level, and minimumLevel.

  7. Understand Fetch Messages response types

    master

    The FetchMessagesResponse can take one of two shapes depending on whether message actions (reactions) were requested:

    1. Standard Response (FetchMessagesForChannelsResponse): Returns a channels object where keys are channel names and values are arrays of FetchedMessage (either RegularMessage or FileMessage).

    2. Response with Actions (FetchMessagesWithActionsResponse): Returned when includeMessageActions is used. Includes a channels object containing FetchedMessageWithActions and a more object for pagination.

    Message Types:

    • RegularMessage: Contains a message field of type Payload and an optional customMessageType.
    • FileMessage: Contains a message field with a file object (including id, name, mime-type, size, and url) and an optional message annotation payload.
  8. Configure Encryption and Crypto Modules

    master

    The React Native client supports data encryption and request signing. If a cipherKey is provided in the configuration, the client will attempt to initialize a LegacyCryptoModule to handle encryption/decryption tasks.

    Environment Control:

    • If process.env.CRYPTO_MODULE is set to 'disabled', the crypto module and token manager (which relies on CBOR) will not be initialized, even if keys are provided.
  9. How PubNub handles browser network connectivity

    master

    The Web SDK can automatically detect changes in the browser's network status by listening to online and offline events on the window object (if listenToBrowserNetworkEvents is enabled, which is the default).

    • When offline is detected: The SDK emits a status event with the category PNNetworkDownCategory. If restore is enabled in the configuration, it will attempt to disconnect(true); otherwise, it calls destroy(true).
    • When online is detected: The SDK emits a status event with the category PNNetworkUpCategory and automatically calls reconnect() to restore connectivity.
  10. Generate access tokens with GrantTokenParameters

    master

    Use GrantTokenParameters to generate time-limited access tokens for specific resources like channels, channel groups, or UUIDs. You can specify exact resource permissions or use RegEx patterns to apply permissions to multiple resources matching a pattern.

    Key constraints:

    • ttl: The token validity in minutes. Minimum: 1, Maximum: 43200 (30 days).
    • meta: Extra metadata attached to the token. Values must be scalars only (no arrays or objects).
    • authorized_uuid: The specific UUID authorized to use this token.
    // Example structure for GrantTokenParameters
    const params: GrantTokenParameters = {
      ttl: 60,
      resources: {
        channels: {
          'my-channel': { read: true, write: true }
        },
        groups: {
          'my-group': { read: true, manage: true }
        },
        uuids: {
          'user-123': { get: true, update: true, delete: true }
        }
      },
      patterns: {
        channels: {
          '^chat-.*': { read: true, write: true }
        }
      },
      meta: {
        role: 'editor'
      },
      authorized_uuid: 'user-123'
    };
  11. Define Custom Data for App Context

    master

    When working with App Context (Metadata for UUIDs, Channels, or Memberships), you can associate custom key-value pairs with these objects. The CustomData type defines the allowed shape for these properties.

    Constraints:

    • Values must be scalars: string, number, boolean, or null.
    • While the type allows for complex structures in some contexts, the App Context filtering language does not support filtering by custom properties.
    • Only arrays or objects are supported for complex values in certain metadata contexts.
    export type CustomData = {
      [key: string]: string | number | boolean | null;
    };
  12. Generate App Context tokens with ObjectsGrantTokenParameters

    master

    Use ObjectsGrantTokenParameters to generate time-limited access tokens specifically for App Context objects (spaces and users).

    Key constraints:

    • ttl: The token validity in minutes. Minimum: 1, Maximum: 43200 (30 days).
    • meta: Extra metadata attached to the token. Values must be scalars only (no arrays or objects).
    • authorizedUserId: The specific userId authorized to use this token.
    // Example structure for ObjectsGrantTokenParameters
    const params: ObjectsGrantTokenParameters = {
      ttl: 1440,
      resources: {
        spaces: {
          'space-id-1': { read: true, write: true }
        }
      },
      patterns: {
        users: {
          'user-.*': { get: true }
        }
      },
      meta: {
        context: 'mobile-app'
      },
      authorizedUserId: 'user-abc'
    };