Install the SDK

To install the SDK, you can use npm or yarn. Run the following command:

npm install --save-dev laravel-echo pusher-js

Initialize the SDK

Set up the Laravel Broadcast driver in your .env file:

.env
BROADCAST_DRIVER=pusher

PUSHER_APP_ID=APP_ID
PUSHER_APP_KEY=APP_KEY
PUSHER_APP_SECRET=APP_SECRET
PUSHER_HOST=ws.pulses.cloud
PUSHER_PORT=443
PUSHER_SCHEME="https"
PUSHER_APP_CLUSTER="pulses"

VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Then, initialize the SDK in your JavaScript file:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    wsHost: import.meta.env.VITE_PUSHER_HOST,
    wsPort: import.meta.env.VITE_PUSHER_PORT,
    wssPort: import.meta.env.VITE_PUSHER_PORT,
    forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

Subscribe to a channel

To subscribe to a channel, you can use the pusher.subscribe method. Run the following command:

const channel = window.Echo.channel('channel-name');

Bind to an event

To bind to an event, you can use the channel.bind method. Run the following command:

window.Echo.listen('channel-name', 'event-name', (data) => {
    console.log('Received event with data:', data);
});

Publish an event from the server

To publish an event from the server, you can use the trigger method. Run the following command:

// First, run 'npm install pusher'
const Pusher = require('pusher');

const pusher = new Pusher('YOUR_APP_KEY', {
    wsHost: 'ws.pulses.cloud',
    encrypted: true,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
    cluster: 'pulses'
});

pusher.trigger('channel-name', 'event-name', {
    message: 'Hello World'
});

If there isn’t an example in a language that you are familiar with then refer to Pusher’s Channels server libraries page to check if anyone has created one in your language.

Unsubscribe from a channel

To unsubscribe from a channel, you can use the leave method. Run the following command:

window.Echo.leave('channel-name');

Disconnect from Pusher

To disconnect from Pusher, you can use the disconnect method. Run the following command:

window.Echo.disconnect();