Gathering detailed insights and metrics for pusher
Gathering detailed insights and metrics for pusher
Gathering detailed insights and metrics for pusher
Gathering detailed insights and metrics for pusher
npm install pusher
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
280 Stars
356 Commits
69 Forks
30 Watching
40 Branches
37 Contributors
Updated on 05 Sept 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-51.8%
57,164
Compared to previous day
Last week
-2.3%
515,755
Compared to previous week
Last month
2.5%
2,093,489
Compared to previous month
Last year
108%
11,021,249
Compared to previous year
In order to use this library, you need to have an account on https://pusher.com/channels. After registering, you will need the application credentials for your app.
This SDK supports Node.js version 10+.
We test the library against a selection of Node.js versions which we update over time. Please refer to test.yml for the set of versions that are currently tested with CI.
If you find any compatibility issues, please raise an issue in the repository or contact support at support@pusher.com. We will happily investigate reported problems ❤️.
You need to be running at least Node.js 10 to use this library.
$ npm install pusher
It's possible to use pusher-http-node with typescript or javascript.
1const Pusher = require("pusher")
1import * as Pusher from "pusher"
All external APIs should have types in index.d.ts.
There are 3 ways to configure the client. First one is just using the Pusher constructor:
1const Pusher = require("pusher") 2 3const pusher = new Pusher({ 4 appId: "APP_ID", 5 key: "APP_KEY", 6 secret: "SECRET_KEY", 7 useTLS: USE_TLS, // optional, defaults to false 8 cluster: "CLUSTER", // if `host` is present, it will override the `cluster` option. 9 host: "HOST", // optional, defaults to api.pusherapp.com 10 port: PORT, // optional, defaults to 80 for non-TLS connections and 443 for TLS connections 11 encryptionMasterKeyBase64: ENCRYPTION_MASTER_KEY, // a base64 string which encodes 32 bytes, used to derive the per-channel encryption keys (see below!) 12})
For specific clusters, you can use the forCluster
function. This is the same as using the cluster
option in the constructor.
1const Pusher = require("pusher") 2 3const pusher = Pusher.forCluster("CLUSTER", { 4 appId: "APP_ID", 5 key: "APP_KEY", 6 secret: "SECRET_KEY", 7 useTLS: USE_TLS, // optional, defaults to false 8 port: PORT, // optional, defaults to 80 for non-TLS connections and 443 for TLS connections 9 encryptionMasterKeyBase64: ENCRYPTION_MASTER_KEY, // a base64 string which encodes 32 bytes, used to derive the per-channel encryption keys (see below!) 10})
You can also specify auth and endpoint options by passing an URL:
1const Pusher = require("pusher") 2 3const pusher = Pusher.forURL( 4 "SCHEME://APP_KEY:SECRET_KEY@HOST:PORT/apps/APP_ID" 5)
You can pass the optional second argument with options, as in forCluster
function.
This is useful for example on Heroku, which sets the PUSHER_URL environment variable to such URL, if you have the Pusher addon installed.
There are a few additional options that can be used in all above methods:
1const Pusher = require("pusher") 2 3const pusher = new Pusher({ 4 // you can set other options in any of the 3 ways described above 5 proxy: "HTTP_PROXY_URL", // optional, URL to proxy the requests through 6 timeout: TIMEOUT, // optional, timeout for all requests in milliseconds 7 keepAlive: KEEP_ALIVE, // optional, enables keep-alive, defaults to false 8})
Asynchronous methods on the Pusher
class (trigger
, get
and post
) return a promise that resolves to a Response
, or rejects with an error.
All operational errors are wrapped into a Pusher.RequestError object.
In case accessing data for invalid WebHooks, an Pusher.WebHookError exception will be thrown from the called method. It is recommended to validate the WebHook before interpreting it.
To send an event to one or more channels use the trigger function. Channel names can contain only characters which are alphanumeric, '_' or '-' and have to be at most 200 characters long. Event name can be at most 200 characters long too.
1pusher.trigger("channel-1", "test_event", { message: "hello world" })
To trigger an event on multiple channels:
1pusher.trigger(["channel-1", "channel-2"], "test_event", { 2 message: "hello world", 3})
You can trigger an event to at most 100 channels at once. Passing more than 100 channels will cause an exception to be thrown.
If you wish to send multiple events in a single HTTP request, you can pass an array of events to pusher.triggerBatch
. You can send up to a maximum of 10 events at once.
1const events = [ 2 { 3 channel: "channel-1", 4 name: "test-event-1", 5 data: { message: "hello world" }, 6 }, 7 { 8 channel: "channel-2", 9 name: "test-event-2", 10 data: { message: "hello another world" }, 11 }, 12] 13 14pusher.triggerBatch(events)
You can trigger a batch of up to 10 events.
Events can be triggered to Authenticated Users
1pusher.sendToUser("user-1", "test_event", { message: "hello world" })
In order to avoid the client that triggered the event from also receiving it, a socket_id
parameter can be added to the params
object. For more information see: http://pusher.com/docs/publisher_api_guide/publisher_excluding_recipients.
1pusher.trigger(channel, event, data, { socket_id: "1302.1081607" }) 2 3pusher.triggerBatch([ 4 { channel: channel, name: name, data: data, socket_id: "1302.1081607" }, 5])
For the channels that were published to, you can request for the number of subscribers or user to be returned in the response body.
1pusher 2 .trigger("presence-my-channel", "event", "test", { info: "user_count,subscription_count" }) 3 .then(response => { 4 if (response.status !== 200) { 5 throw Error("unexpected status") 6 } 7 // Parse the response body as JSON 8 return response.json() 9 ) 10 .then(body => { 11 const channelsInfo = body.channels 12 // Do something with channelsInfo 13 }) 14 .catch(error => { 15 // Handle error 16 })
1const batch = [ 2 { 3 channel: "my-channel", 4 name: "event", 5 data: "test1", 6 info: "subscription_count", 7 }, 8 { 9 channel: "presence-my-channel", 10 name: "event", 11 data: "test2", 12 info: "user_count,subscription_count", 13 }, 14] 15pusher 16 .triggerBatch(batch) 17 .then((response) => { 18 if (response.status !== 200) { 19 throw Error("unexpected status") 20 } 21 // Parse the response body as JSON 22 return response.json() 23 }) 24 .then((body) => { 25 body.batch.forEach((attributes, i) => { 26 process.stdout.write( 27 `channel: ${batch[i].channel}, name: ${batch[i].name}, subscription_count: ${attributes.subscription_count}` 28 ) 29 if ("user_count" in attributes) { 30 process.stdout.write(`, user_count: ${attributes.user_count}`) 31 } 32 process.stdout.write("\n") 33 }) 34 }) 35 .catch((error) => { 36 console.error(error) 37 })
This library supports end-to-end encryption of your private channels. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them. You can enable this feature by following these steps:
You should first set up Private channels. This involves creating an authorization endpoint on your server.
Next, generate your 32 byte master encryption key, encode it as base64 and pass it to the Pusher constructor.
This is secret and you should never share this with anyone. Not even Pusher.
1openssl rand -base64 32
1const pusher = new Pusher({ 2 appId: "APP_ID", 3 key: "APP_KEY", 4 secret: "SECRET_KEY", 5 useTLS: true, 6 encryptionMasterKeyBase64: "<KEY GENERATED BY PREVIOUS COMMAND>", 7})
Channels where you wish to use end-to-end encryption should be prefixed with private-encrypted-
.
Subscribe to these channels in your client, and you're done! You can verify it is working by checking out the debug console on the https://dashboard.pusher.com/ and seeing the scrambled ciphertext.
Important note: This will not encrypt messages on channels that are not prefixed by private-encrypted-
.
Limitation: you cannot trigger a single event on multiple channels in a call to trigger
, e.g.
1pusher.trigger(["channel-1", "private-encrypted-channel-2"], "test_event", { 2 message: "hello world", 3})
Rationale: the methods in this library map directly to individual Channels HTTP API requests. If we allowed triggering a single event on multiple channels (some encrypted, some unencrypted), then it would require two API requests: one where the event is encrypted to the encrypted channels, and one where the event is unencrypted for unencrypted channels.
To authenticate users during sign in, you can use the authenticateUser
function:
1const userData = { 2 id: "unique_user_id", 3 name: "John Doe", 4 image: "https://...", 5} 6const auth = pusher.authenticateUser(socketId, userData)
The userData
parameter must contain an id
property with a non empty string. For more information see: http://pusher.com/docs/authenticating_users
In order to terminate a user's connections, the user must have been authenticated. Check the Server user authentication docs for the information on how to create a user authentication endpoint.
To terminate all connections established by a given user, you can use the terminateUserConnections
function:
1pusher.terminateUserConnections(userId)
Please note, that it only terminates the user's active connections. This means, if nothing else is done, the user will be able to reconnect. For more information see: Terminating user connections docs.
To authorise your users to access private channels on Pusher Channels, you can use the authorizeChannel
function:
1const auth = pusher.authorizeChannel(socketId, channel)
For more information see: http://pusher.com/docs/authenticating_users
Using presence channels is similar to private channels, but you can specify extra data to identify that particular user:
1const channelData = { 2 user_id: 'unique_user_id', 3 user_info: { 4 name: 'Phil Leggetter' 5 twitter_id: '@leggetter' 6 } 7}; 8const auth = pusher.authorizeChannel(socketId, channel, channelData);
The auth
is then returned to the caller as JSON.
For more information see: http://pusher.com/docs/authenticating_users
It's possible to query the state of the application using the pusher.get
function.
1pusher.get({ path: path, params: params })
The path
property identifies the resource that the request should be made to and the params
property should be a map of additional query string key and value pairs.
Params can't include following keys:
The following example shows how to handle the result of a get
:
1pusher 2 .get({ path: "/channels", params: {} }) 3 .then(response => { 4 if (response.status !== 200) { 5 throw Error("unexpected status") 6 } 7 // Parse the response body as JSON 8 return response.json() 9 ) 10 .then(body => { 11 const channelsInfo = body.channels 12 // Do something with channelsInfo 13 }) 14 .catch(error => { 15 // Handle error 16 }) 17})
1pusher.get({ path: "/channels", params: params })
Information on the optional params
and the structure of the returned JSON is defined in the REST API reference.
1pusher.get({ path: "/channels/[channel_name]", params: params })
Information on the optional params
option property and the structure of the returned JSON is defined in the REST API reference.
1pusher.get({ path: "/channels/[channel_name]/users" })
The channel_name
in the path must be a presence channel. The structure of the returned JSON is defined in the REST API reference.
The library provides a simple helper for WebHooks, which can be accessed via Pusher instances:
1const webhook = pusher.webhook(request)
Requests must expose following fields:
Since neither Node.js nor express provide the body in the request, your application needs to read it and assign to the request object. See examples/webhook_endpoint.js for a simple webhook endpoint implementation using the express framework.
Headers object must contain following headers:
After instantiating the WebHook object, you can use its following methods:
Validates the content type, body format and signature of the WebHook and returns a boolean. Your application should validate incoming webhooks, otherwise they could be faked.
Accepts an optional parameter containing additional application tokens (useful e.g. during migrations):
1const webhook = pusher.webhook(request) 2// will check only the key and secret assigned to the pusher object: 3webhook.isValid() 4// will also check two additional tokens: 5webhook.isValid([ 6 { key: "x1", secret: "y1" }, 7 { key: "x2", secret: "y2" }, 8])
Returns the parsed WebHook body. Throws a Pusher.WebHookError if the WebHook is invalid, so please check the isValid
result before accessing the data.
1// will return an object with the WebHook data 2webhook.getData()
Please read the WebHooks documentation to find out what fields are included in the body.
Returns events included in the WebHook as an array. Throws a Pusher.WebHookError if the WebHook is invalid, so please check the isValid
result before accessing the events.
1// will return an array with the events 2webhook.getEvents()
Returns the Date object for the time when the WebHook was sent from Channels. Throws a Pusher.WebHookError
if the WebHook is invalid, so please check the isValid
result before accessing the time.
1// will return a Date object 2webhook.getTime()
If you wanted to send the REST API requests manually (e.g. using a different HTTP client), you can use the createSignedQueryString
method to generate the whole request query string that includes the auth keys and your parameters.
1pusher.createSignedQueryString({ 2 method: "POST", // the HTTP request method 3 path: "/apps/3/events", // the HTTP request path 4 body: '{"name":"foo","channel":"donuts","data":"2-for-1"}', // optional, the HTTP request body 5 params: {}, // optional, the query params 6})
The params
object can't contain following keys, as they are used to sign the request:
The tests run using Mocha. Make sure you've got all required modules installed:
npm install
You can run local integration tests without setting up a Pusher Channels app:
npm run local-test
In order to run the full test suite, first you need a Pusher Channels app. When starting mocha, you need to set the PUSHER_URL environment variable to contain your app credentials, like following:
PUSHER_URL='http://KEY:SECRET@api-CLUSTER.pusher.com/apps/APP_ID' npm test
This library is based on the work of:
This code is free to use under the terms of the MIT license.
No vulnerabilities found.
No security vulnerabilities found.