Pusher Channels JavaScript Client

8.5.0 · active · verified Sun Apr 19

The `pusher-js` library provides a robust client-side solution for real-time communication via Pusher Channels. It supports a wide array of JavaScript environments, including web browsers, React Native, Node.js, and web workers, offering a consistent API across platforms. Currently at stable version 8.5.0, the library demonstrates an active release cadence, frequently delivering security updates via dependency pinning and introducing new features like the `switchCluster` method for dynamic cluster changes without disrupting existing channel subscriptions. Its key differentiators include extensive platform compatibility, resilient fallback mechanisms (WebSockets, HTTP), and dedicated support for both public and private channels, including an optional build specifically for encrypted channels. It is designed purely for client-side interaction with the Pusher service, distinct from the `pusher-http-node` server-side library.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a Pusher client, connecting, subscribing to a public channel, and binding to a custom event. Includes handling connection status.

import Pusher from 'pusher-js';

// Replace with your actual Pusher app key and cluster
const PUSHER_APP_KEY = process.env.PUSHER_APP_KEY ?? 'YOUR_APP_KEY';
const PUSHER_APP_CLUSTER = process.env.PUSHER_APP_CLUSTER ?? 'eu'; // e.g., 'eu', 'us2'

if (PUSHER_APP_KEY === 'YOUR_APP_KEY') {
  console.warn('Pusher app key not set. Using a placeholder. Replace YOUR_APP_KEY and PUSHER_APP_CLUSTER with your actual credentials.');
}

const pusher = new Pusher(PUSHER_APP_KEY, {
  cluster: PUSHER_APP_CLUSTER,
  forceTLS: true // Always use TLS for production
});

pusher.connection.bind('connected', () => {
  console.log('Pusher client connected!');
});

pusher.connection.bind('disconnected', () => {
  console.log('Pusher client disconnected!');
});

const channel = pusher.subscribe('my-channel');

channel.bind('my-event', function(data: any) {
  console.log('Received event on my-channel:', data);
});

// To simulate receiving an event (typically sent from a server):
// setTimeout(() => {
//   console.log('Simulating event trigger...');
//   // This part would typically be handled by your server sending an event
//   // For client-side simulation, you might use a debug API or similar.
// }, 5000);

console.log('Pusher client initialized and attempting to connect...');

// You can switch cluster dynamically (since v8.5.0)
// setTimeout(() => {
//   console.log('Switching cluster to us2...');
//   pusher.switchCluster('us2');
// }, 10000);

view raw JSON →