The Pusher connection

The Pusher connection is the fundamental means of communication with the service. It is a bi-directional connection and is able to receive messages as well as emit messages from the server.

Connecting to Pusher

When you create a new Pusher object you are automatically connected to Pusher.

var pusher = new Pusher(applicationKey, options);
  • applicationKey (String) - The application key is a string which is globally unique to your application. It can be found in the API Access section of your application within the Pusher user dashboard.
  • options (Object) [optional] - See Pusher options parameter below.

Pusher options parameter

The options parameter on the Pusher constructor is an optional parameter used to apply configuration on a newly created Pusher instance.

  encrypted: true, // true/false
  auth: {
    params: { // {key: value} pairs
      param1: 'value1',
      param2: 'value2'
    headers: { // {key: value} pairs
      header1: 'value1',
      header2: 'value2'

The options are:

encrypted (Boolean)

It’s possible to define if the connection should be made over an encrypted connection. For more information see Encrypting connections.

authEndpoint (String)

Endpoint on your server that will return the authentication signature needed for private and presence channels. Defaults to '/pusher/auth'.

For more information see authenticating users.

Note: If authentication fails a subscription_error event is triggered on the channel. For more information see handling authentication problems.

authTransport (String)

Defines how the authentication endpoint, defined using authEndpoint, will be called. There are two options available:

  • ajax - The default option where an XMLHttpRequest object will be used to make a request. The parameters will be passed as POST parameters.
  • jsonp - The authentication endpoint will be called by a <script> tag being dynamically created pointing to the endpoint defined by authEndpoint. This can be used when the authentication endpoint is on a different domain to the web application. The endpoint will therefore be requested as a GET and parameters passed in the query string.

For more information see the Channel authentication transport section of the authenticating users docs.

auth (Object)

Note: this feature was introduced in version 1.12 of the Pusher JavaScript library.

The auth option lets you send additional information with the authentication request. See authenticating users.

When creating a Pusher instance the options parameter can have an auth property set as follows:

var pusher = new Pusher('app_key', {
  auth: {
    params: {
      CSRFToken: 'some_csrf_token'
auth.params (Object)

Additional parameters to be sent when the channel authentication endpoint is called. When using ajax authentication the parameters are passed as additional POST parameters. When using jsonp authentication the parameters are passed as GET parameters. This can be useful with web application frameworks that guard against CSRF (Cross-site request forgery).

auth.headers (Object)

Only applied when using ajax authentication

Provides the ability to pass additional HTTP Headers to the channel authentication endpoint when authenticating a channel. This can be useful with some web application frameworks that guard against CSRF (Cross-site request forgery).

var pusher = new Pusher('app_key', {
  auth: {
    headers: {
      'X-CSRF-Token': 'some_csrf_token'

cluster (String)

Allows connecting to a different datacenter by setting up correct hostnames and ports for the connection. Optional, when not supplied, will connect to the default us-east cluster.

// will connect to the 'eu' cluster
var pusher = new Pusher('app_key', { cluster: 'eu' });

disableFlash (Boolean)

Disables Flash fallback, leaving only WebSockets and HTTP fallback.

disableStats (Boolean)

Disables stats collection, so that connection metrics are not submitted to Pusher’s servers.

In the following examples, _client is a strong instance variable. The instance returned by the pusherWithKey:*: methods will be auto-released, according to standard Objective-C return conventions. You must retain the client otherwise it will be auto-released before anything useful happens causing silent failures and unexpected behaviour.

_client = [PTPusher pusherWithKey:@"YOUR_APP_KEY"];


It’s possible to define if the connection should be made over an encrypted connection. For more information see Encrypting connections.


It is recommended to implement the PTPusherDelegate protocol in order to be notified when significant connection events happen such as connection errors, disconnects and retries.

See Connection states.


When calling the above method, the connection will be established immediately. If you want to defer connection, you can do so:

_client = [PTPusher pusherWithKey:@"YOUR_APP_KEY" connectAutomatically:NO];

When you are ready to connect, call

[_client connect]


By default if a connection is lost the instance will not automatically reconnect. In order for automatic reconnection to be made reconnectAutomatically must be set.

_client = [PTPusher pusherWithKey:@"YOUR_APP_KEY" delegate:self];
_client.reconnectAutomatically = YES;

See Connection states.


When automatic reconnection has been set the time between the detected disconnection and the reconnection attempt can be configured:

_client = [PTPusher pusherWithKey:@"YOUR_APP_KEY" delegate:self];
_client.reconnectAutomatically = YES;
_client.reconnectDelay = 10;

The default value is 5 seconds.

See Connection states.


_client = [PTPusher pusherWithKey:@"YOUR_APP_KEY"];
_client.authorizationURL = "";

When subscribing to private or presence channels the subscription has to be authenticated via a server. The URL set via the authorizationURL defines the authentication endpoint.

See authenticating users.

Encrypting connections

A Pusher client can be configured to only connect over encrypted (SSL) connections. An application that uses SSL should use this option to ensure connection traffic is encrypted. It is also possible to force connections to use SSL by enabling the Encrypted setting within an application’s dashboard settings.

var pusher = new Pusher('app_key', { encrypted: true } );

By default the connection to Pusher will be made over an encrypted connection. It is possible to change by setting encrypted to NO.

_client = [PTPusher pusherWithKey:@"YOUR_APP_KEY" encrypted:NO];

Detecting Connection Limits

Connection limits are currently only enforced on Sandbox plans. You will receive an email if your account exceeds your connection limit. If you are on a Sandbox plan and want to avoid connection limits upgrade your account. For more information on plan limits see pricing.

When connection limits are reached additional connections over the limit will be rejected. You can capture the rejection by binding to the error event on the pusher.connection object.

var pusher = new Pusher('app_key');
pusher.connection.bind( 'error', function( err ) { 
  if( === 4004 ) {
    log('>>> detected limit error');

Disconnecting from Pusher

It is also possible to disconnect from Pusher.


Note: connections automatically close when a user navigates to another web page or closes their web browser so there is no need to do this manually.

[_client disconnect];

Connection States

When working with our Pusher client library, you can monitor the state of the connection so that you can notify users about expected behaviour.

This document refers to version 1.9.0 of our library and above. Previous versions used the following events which have now been removed: pusher:connection_established and pusher:connection_failed.

There are multiple ways to use the connection state API:

  • Bind to individual state change events
  • Bind to all state change events
  • Query the state directly

Additionally, the reconnect mechanism is now more transparent. This means that you can display messages that tell the user when the service might be connected.

Available states

You can access the current state as pusher.connection.state and bind to a state change using pusher.connection.bind('connected', function() {...})

initializedInitial state. No event is emitted in this state.
connectingAll dependencies have been loaded and Pusher is trying to connect. The connection will also enter this state when it is trying to reconnect after a connection failure.
connectedThe connection to Pusher is open and authenticated with your app.
unavailableThe connection is temporarily unavailable. In most cases this means that there is no internet connection. It could also mean that Pusher is down, or some intermediary is blocking the connection. In this state, Pusher will automatically retry the connection every ten seconds. connecting_in events will still be triggered.
failedPusher is not supported by the browser. This implies that WebSockets are not natively available, Flash is not available, and an HTTP-based transport could not be found.
disconnectedThe Pusher connection was previously connected and has now intentionally been closed.

Additionally a connecting_in event is periodically emitted whilst the connection is in the connecting or unavailable state. This event indicates the time in seconds before another connection attempt is made.

Example state changes

Given a supported browser and functioning internet connection, the following states are expected:

initialized -> connecting -> connected

Temporary failure of the Pusher connection will cause

connected -> connecting -> connected

If an internet connection disappears

connected -> connecting -> unavailable (after ~ 30s)

When the internet connection becomes available again

unavailable -> connected

In the case that Pusher is not supported:

initialized -> failed

Binding to events

Each Pusher instance now has a connection object which manages the current state of the Pusher connection and allows binding to state changes:

var pusher = new Pusher('YOUR_APP_KEY');

pusher.connection.bind('connected', function() {
  $('div#status').text('Real time is go!');

It is also possible bind to the connecting_in event. This will give you the time until the next connection attempt.

pusher.connection.bind('connecting_in', function(delay) {
  alert("I haven't been able to establish a connection for this feature.  " +
        "I will try again in " + delay + " seconds.")

Note: this isn’t a countdown, and is not fired every second.

Binding to all state changes

There’s an extra state_change utility event that fires for all state changes:

pusher.connection.bind('state_change', function(states) {
  // states = {previous: 'oldState', current: 'newState'}
  $('div#status').text("Pusher's current state is " + states.current);
_client = [PTPusher pusherWithKey:@"YOUR_APP_KEY" delegate:self];

The nature of a mobile device is that connections will come and go. There are a number of things you can do to ensure that your Pusher connection remains active for as long as you have a network connection and reconnects after network connectivity has been re-established.

The following examples use Apple’s Reachability class (version 2.2) to check the network reachability status. Apple recommends that in most circumstances, you do not do any pre-flight checks and simply try and open a connection. This example follows this advice.

You can configure libPusher to automatically try and re-connect if it disconnects or it initially fails to connect.

PTPusher *client = [PTPusher pusherWithKey:@"YOUR_APP_KEY" delegate:self];
client.reconnectAutomatically = YES;
client.reconnectDelay = 30; // defaults to 5 seconds

What you don’t want to do is keep on blindly trying to reconnect if there is no available network and therefore no possible way a connection could be successful. You should implement the PTPusherDelegate methods pusher:connectionDidDisconnect: and pusher:connection:didFailWithError:.

- (void)pusher:(PTPusher *)client connectionDidDisconnect:(PTPusherConnection *)connection
  Reachability *reachability = [Reachability reachabilityForInternetConnection];
  if ([reachability currentReachabilityStatus] == NotReachable) {
    // there is no point in trying to reconnect at this point
    client.reconnectAutomatically = NO;
    // start observing the reachability status to see when we come back online
    [[NSNotificationCenter defaultCenter] 
    [reachability startNotifier];

The implementation of pusher:connection:didFailWithError: will look similar to the above although you may wish to do some further checking of the error.

Now you simply need to wait for the network to become reachable again; it’s no guarantee that you will be able to establish a connection but it is an indicator that it would be reasonable to try again.

- (void)reachabilityChanged:(NSNotification *)note
  Reachability *reachability = note.object;
  if ([reachability currentReachabilityStatus] != NotReachable) {
    // we seem to have some kind of network reachability, so try again
    PTPusher *pusher = <# get the pusher instance #>
    [pusher connect];
    // we can stop observing reachability changes now
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [reachability stopNotifier];
    // re-enable auto-reconnect
    pusher.reconnectAutomatically = YES;

Finally, you may prefer to not turn on automatic reconnection immediately, but instead wait until you’ve successfully connected. You could do this by implementing the pusher:connectionDidConnect: delegate method:

- (void)pusher:(PTPusher *)client connectionDidConnect:(PTPusherConnection *)connection
  client.reconnectAutomatically = YES;

Doing it this way means you do not need to re-enable auto-reconnect in your Reachability notification handler as it will happen automatically once you have connected.

If Pusher disconnects but Reachability indicates that the network is reachable, it is possible that there is a problem with the Pusher service. In this situation, you would be advised to simply allow libPusher to try and reconnect automatically (if you have enabled this).

You may want to implement the pusher:connectionWillReconnect:afterDelay: delegate method and keep track of the number of retry attempts and gradually back off your retry attempts by increasing the reconnect delay after a number of retry attempts have failed. This stops you from constantly trying to connect to Pusher while it is experience issues.

Querying the connection state

var state = pusher.connection.state;

Where Next?

Have you tried using the search to find what you’re after? If you still have a question then get in touch with us and let us help you out.