Monitor and respond to connection status changes
PubNub's SDK manages the subscribe loop and reconnection automatically. This page shows how to expose that behavior to your application so you can react to connection state changes.
Attach a status listener to your PubNub client so your application can tell a healthy idle connection from a lost one, and act when the SDK stops retrying. Attach it to the PubNub client object, not to an individual subscription or subscription set, and attach it once per client.
Before you start, make sure you have:
- An initialized PubNub client with your keyset's keys and a
userId. Refer to Quickstart. - At least one active subscription. The statuses on this page describe the subscribe connection, so a client that never subscribes emits none of them.
Nothing needs enabling in the Admin Portal, and status events need no add-on.
If a listener is already attached and you only need to know what to do with each status, skip to Branch on the status category.
Add the listener, then subscribe
Add the listener to the client before you subscribe, because a listener receives only the events emitted after it's attached.
- JavaScript
- Swift
- Kotlin
- Java
- C#
1
1
1
1
1
Most other SDKs document the same call in the Add connection status listener section of their Publish/Subscribe API reference, for example Python.
Keep the listener attached for the life of the client. Adding a second listener for the same purpose gives you duplicate status events to deduplicate.
Branch on the status category
Status category names vary by SDK
The five categories below are conceptual. Every SDK exposes them differently: different constant names, different fields on the event object, and not every SDK emits all five. Check your SDK's status events reference before writing this code, for example JavaScript.
Compare the category on each event against your SDK's own constants, for example PNConnectedCategory in JavaScript.
| Status | What to do |
|---|---|
Connected | Clear any offline indicator in your UI. If the client had been disconnected before this event, run your catch-up path now. |
Subscription changed | Update whatever your application tracks about the current subscription from the channel and channel-group arrays on the event. Don't treat it as a reconnect. |
Disconnected | Treat it as expected, because it follows your own request to stop. Resume the connection with your SDK's reconnect method rather than by calling subscribe again. |
Disconnected unexpectedly | Show offline state and read the error field. The retries are already spent, so decide here whether to recover missed messages, and reconnect when it makes sense for the user. |
Connection error | Read the error field before doing anything else. If it reports access denied, refresh the token. If it reports a network failure, reconnect when connectivity returns. |
In a browser, the JavaScript SDK also emits two network-level categories ahead of these five: PNNetworkDownCategory and PNNetworkUpCategory. See Detect a browser network drop sooner.
Give Connection error and Disconnected unexpectedly separate handling even when they show the same offline UI, because repeating a request that was rejected reproduces the rejection. For why the two differ, refer to Two failures that mean different things.
Don't start your own retry loop while you wait for a status. The JavaScript SDK's current subscription workflow handles intermediate connecting and reconnecting states internally, emitting no status event until a retry sequence succeeds or gives up. Treat that silence as the SDK's own reconnection policy still working.
Resume the connection
Call the reconnect method when the client sits in Disconnected after your own stop request, and after you replace a rejected token. Subscribing again doesn't restart the subscribe loop.
- JavaScript
- Swift
- Kotlin
- Java
- C#
1
1
1
1
1
Reconnect in response to a user action or a status event rather than on a timer, because the SDK already applies its own reconnection policy to a failed request.
Refresh a token when a status reports access denied
Follow this path only if your keyset uses Access Manager. A retry policy can't clear a rejected token, so this handling is yours.
- Read the
errorfield on theConnection errorevent. In JavaScript, an access failure arrives asPNConnectionErrorCategorywithPNAccessDeniedCategorynested in that field. - Request a new token from your own server for the same
userId, scoped withreadpermission on the channels and channel groups the client subscribes to. - Set the new token on the client:
- JavaScript
- Swift
- Kotlin
- Java
- C#
1
1
1
1
1
Then resume the connection, because setting the token doesn't restart the subscribe loop on its own.
The secret key grants privileged access to your PubNub application. It must remain on a trusted server and must never be included in client applications.
For the grant call itself, refer to How to update an expired token.
Detect a browser network drop sooner
Apply this step only to the JavaScript SDK running in a browser. Other environments have no equivalent signal and reach a terminal status only after the retries are spent.
- Leave
listenToBrowserNetworkEventsat its default so the SDK also emitsPNNetworkDownCategoryandPNNetworkUpCategory. UsePNNetworkDownCategoryto show offline state immediately instead of waiting for retries to finish. - Leave
restoreat its default so the SDK keeps the current timetoken and the channel and channel-group list across the drop. - If you set
restore: false, track the subscribed channels and channel groups in your own cache and resubscribe whenPNNetworkUpCategoryarrives. The SDK resets both on network loss in that mode.
Confirm the current defaults for both options in the JavaScript configuration reference.
Verify the listener
Test the failure paths before you rely on them.
- Subscribe to a channel and confirm you receive
Connected. - In your browser's developer tools, switch the network to Offline. In a browser, expect
PNNetworkDownCategoryright away. In other environments, wait for the retries to run out and expectDisconnected unexpectedly. - Switch the network back on. Expect
PNNetworkUpCategoryin a browser, thenConnected. - To exercise the access-denied path, initialize a client with a token that has no
readpermission on the channel, then subscribe. ExpectConnection errorcarrying an access-denied error.
Log the category and the error field in each case. A test that only checks that messages resume tells you nothing about which status your code took.
Related tasks
- How to receive messages effectively to recover messages published while the client was disconnected.
- How to stop receiving messages for the intentional disconnect that produces
Disconnected. - How to update an expired token for the server-side half of a token refresh.
- Connection management for what the SDK retries on its own and what each status means.