Pusher Channels JavaScript Client

repository·master·Indexed 24 days ago

https://github.com/pusher/pusher-js

A JavaScript library for subscribing to real-time channels and receiving events in web browsers, web workers, and Node.js environments. Version 8.6.0 supports public, private, and encrypted channels, with TypeScript declarations provided since v5.1.0. Note that React Native support is deprecated in favor of the official Pusher React Native SDK.

Tokens
4.2K
Snippets
13
Records
30
Agent score
79%

What's inside pusher-js

  1. Understand Pusher connection states

    master

    The pusher.connection object tracks the current state of the connection. Possible states include:

    StateDescription
    initializedInitial state. No event is emitted.
    connectingAttempting to connect or reconnecting after failure.
    connectedConnection is open and authenticated.
    unavailableConnection is temporarily unavailable (e.g., no internet or service down).
    failedBrowser does not support WebSockets and no HTTP fallback was found.
    disconnectedConnection was intentionally closed.
  2. Install pusher-js via CDN

    master

    For direct inclusion in HTML pages, use the Pusher CDN. As with the NPM installation, you must choose between the standard build and the encryption-enabled build.

    Standard build:

    <script src="https://js.pusher.com/7.0/pusher.min.js"></script>

    Encrypted channels build:

    <script src="https://js.pusher.com/7.0/pusher-with-encryption.min.js"></script>
    <script src="https://js.pusher.com/7.0/pusher.min.js"></script>
  3. Install pusher-js for Web Workers

    master

    To use pusher-js within a Web Worker, you can either import the worker script directly from the CDN or import the worker entrypoint if you are using a bundler.

    Using CDN (importScripts):

    importScripts('https://js.pusher.com/7.0/pusher.worker.min.js');

    Encrypted channels (CDN):

    importScripts('https://js.pusher.com/7.0/pusher-with-encryption.worker.min.js');

    Using a bundler:

    import Pusher from 'pusher-js/worker';

    Encrypted channels (Bundler):

    import Pusher from 'pusher-js/worker/with-encryption';

    Note: The Web Workers implementation is currently not compatible with Internet Explorer.

    importScripts('https://js.pusher.com/7.0/pusher.worker.min.js');
  4. Use TypeScript with pusher-js

    master

    TypeScript declarations are provided since v5.1.0. While most functionality works out of the box, you can import specific types directly from the package:

    import Pusher from 'pusher-js';
    import * as PusherTypes from 'pusher-js';
    
    var presenceChannel: PusherTypes.PresenceChannel;
    import Pusher from 'pusher-js';
    import * as PusherTypes from 'pusher-js';
    
    var presenceChannel: PusherTypes.PresenceChannel;
  5. Install pusher-js for Web

    master

    You can install pusher-js for web applications using NPM or Yarn. Note that the default builds do not include encryption primitives to keep bundle sizes small. If you require encrypted channels, you must specifically import the with-encryption build.

    Using Yarn or NPM

    Install the package:

    yarn add pusher-js

    Then import it in your code:

    Standard build:

    import Pusher from 'pusher-js';
    // or for non-ES6 modules:
    const Pusher = require('pusher-js');

    Encrypted channels build:

    import Pusher from 'pusher-js/with-encryption';
    // or for non-ES6 modules:
    const Pusher = require('pusher-js/with-encryption');
  6. Initialize a Pusher connection

    master

    To establish a connection to Pusher Channels, instantiate the Pusher class with your APP_KEY and a configuration object containing your cluster.

    const pusher = new Pusher(APP_KEY, {
      cluster: APP_CLUSTER,
    });
  7. Install pusher-js for Node.js

    master

    After installing pusher-js via an NPM-compatible package manager, you can use it in Node.js by importing the module:

    import Pusher from 'pusher-js';

    Note: For standard WebWorkers, this build will use HTTP as a fallback. For ServiceWorkers, there is currently no support for HTTP fallbacks because the XMLHttpRequest API is unavailable.

    import Pusher from 'pusher-js';
  8. Self-hosting pusher-js files

    master

    If you host pusher-js yourself, you must ensure that all dependency files (like json2.js and sockjs.js) are accessible at the same host and versioned directory structure, as the library loads fallbacks dynamically.

    To build a self-hosted version:

    1. Clone the repo and initialize submodules.
    2. Run make web with CDN_HTTP and CDN_HTTPS environment variables set.
    3. Host the files in dist/web following this pattern:
      • http://example.com/pusher-js/7.0.0/pusher.js
      • http://example.com/pusher-js/7.0.0/json2.js
      • http://example.com/pusher-js/7.0.0/sockjs.js

    Minified versions should use the .min suffix (e.g., pusher.min.js).

    $ CDN_HTTP='http://your.http.url' CDN_HTTPS='https://your.https.url' make web
  9. Configure user authentication

    master

    The userAuthentication object configures how the client authenticates users (e.g., for private channels).

    Available keys:

    • endpoint (String): Server endpoint for the authentication signature. Defaults to /pusher/auth.
    • transport (String): Method used to call the endpoint. Options: ajax (default, uses XMLHttpRequest with POST) or jsonp (uses <script> tag with GET).
    • params (Object): Additional parameters sent with the request (POST for ajax, GET for jsonp).
    • headers (Object): HTTP Headers (only for ajax transport).
    • paramsProvider (Function): Dynamically retrieves parameters at the time of the request.
    • headersProvider (Function): Dynamically retrieves headers at the time of the request.
    • customHandler (Function): A custom function to handle the request instead of the specified endpoint.
  10. Configure connection transports

    master

    You can control which connection transports (e.g., WebSockets, XHR) the library uses.

    Available web transports: ws, wss, xhr_streaming, xhr_polling, sockjs.

    • enabledTransports (Array): A whitelist of allowed transports. Note: To use secure WebSockets (wss), you must include ws in this list and set forceTLS: true.
    • disabledTransports (Array): A blacklist of transports to avoid. This overwrites any whitelist provided by enabledTransports.

    Example: Only use secure WebSockets:

    const pusher = new Pusher(APP_KEY, {
      cluster: APP_CLUSTER,
      enabledTransports: ['ws'],
      forceTLS: true
    });
    // Only use secure WebSockets
    const pusher = new Pusher(APP_KEY, {
      cluster: APP_CLUSTER,
      enabledTransports: ['ws'],
      forceTLS: true
    });
  11. Configure channel authorization

    master

    The channelAuthorization object configures how the client authorizes access to specific channels (required for private and presence channels).

    Available keys:

    • endpoint (String): Server endpoint for the authorization signature. Defaults to /pusher/auth.
    • transport (String): Method used to call the endpoint. Options: ajax (default, uses XMLHttpRequest with POST) or jsonp (uses <script> tag with GET).
    • params (Object): Additional parameters sent with the request (POST for ajax, GET for jsonp).
    • headers (Object): HTTP Headers (only for ajax transport).
    • paramsProvider (Function): Dynamically retrieves parameters at the time of the request.
    • headersProvider (Function): Dynamically retrieves headers at the time of the request.
    • customHandler (Function): A custom function to handle the request instead of the specified endpoint.
  12. Configure Channel Authorization and User Authentication

    master

    When initializing Pusher, you can provide authentication options to handle private or presence channel authorization and user authentication. You have two ways to configure this:

    1. Standard Authentication: Provide an endpoint and transport (either 'ajax' or 'jsonp') to allow the client to make requests to your server.
    2. Custom Authentication Handler: Provide a customHandler function to intercept the authentication request and handle it manually (e.g., using a different transport or custom logic).

    Authentication Types

    • Channel Authorization: Used for private and presence channels. Requires a handler that accepts socketId and channelName and returns ChannelAuthorizationData containing an auth string.
    • User Authentication: Used for user-based authentication. Requires a handler that accepts socketId and returns UserAuthenticationData containing an auth string and user_data string.