# Connection
The `Connection` interface represents the connection to Ably and provides methods to inspect the connection state, listen for state changes, and explicitly open or close the connection. Access it via the `connection` property of a [`Realtime`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md) client instance.
#### Javascript
```
const connection = realtime.connection;
```
## Properties
The `Connection` interface has the following properties:
| Property | Description | Type |
| --- | --- | --- |
| id | A unique public identifier for this connection, used to identify this member in presence events and messages. | String |
| state | The current [connection state](https://ably.com/docs/connect/states.md#connection-states) of this connection. | |
| errorReason | When a connection failure occurs this property contains the error reason. | [ErrorInfo](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#errorinfo) or Undefined |
| key | A unique private connection key used to recover or resume a connection, assigned by Ably. When recovering a connection explicitly, the `recoveryKey` is used in the [`clientOptions.recover`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#constructor-params) option as it contains both the `key` and the last message serial. This private connection key can also be used by other REST clients to [publish on behalf of this realtime client](https://ably.com/docs/pub-sub/advanced.md#publish-on-behalf). | String |
| Value | Description |
| --- | --- |
| initialized | A connection object has been initialized but no connection has yet been attempted. |
| connecting | A connection attempt has been initiated. The `connecting` state is entered as soon as the SDK has completed initialization, and is reentered each time connection is re-attempted following disconnection. |
| connected | A connection exists and is active. |
| disconnected | A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt is unsuccessful. In the disconnected state the SDK will periodically attempt to open a new connection. |
| suspended | A long term failure condition. No current connection exists because there is no network connectivity or no host is available. The suspended state is entered after a failed connection attempt has been made and a more or less immediate reconnection attempt has failed. In the suspended state, the SDK will periodically attempt to open a new connection every 30 seconds. Once reconnected, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the [History API](https://ably.com/docs/storage-history/history.md). |
| closing | An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection will be forcibly terminated and the connection state will become `closed`. |
| closed | The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the SDK, and clients may not publish messages, subscribe to channels, or be present in any channels. Any channel objects that existed before the connection was closed are released. |
| failed | This state is entered if the SDK encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service (for example an attempt to connect with invalid credentials), or a local terminal error (for example the token in use has expired and the SDK does not have any way to renew it). In the failed state, no reconnection attempts are made automatically by the SDK, and clients may not publish messages, subscribe to channels, or be present in any channels. |
## Connect to Ably
`connection.connect(): void`
Explicitly calling `connect()` is unnecessary unless [`clientOptions.autoConnect`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#constructor-params) is `false`. Unless already `connected` or `connecting`, this method causes the connection to open, entering the `connecting` state.
### Javascript
```
realtime.connection.connect();
await realtime.connection.once('connected');
```
## Close the connection
`connection.close(): void`
Causes the connection to close, entering the `closing` state. Once `closed`, the SDK will not attempt to re-establish the connection without an explicit call to [`connect()`](#connect).
### Javascript
```
realtime.connection.close();
```
## Register a state change listener
`connection.on(event: ConnectionEvent, listener: connectionEventCallback): void`
Register the given listener for the specified `ConnectionEvent` on the `Connection`. The listener is passed a `ConnectionStateChange` object that contains the current state, previous state, the event, and an optional reason for the event or state change.
`connection.on(events: ConnectionEvent[], listener: connectionEventCallback): void`
Registers the listener for each event in the array.
`connection.on(listener: connectionEventCallback): void`
Register the given listener for all `ConnectionEvent`s on the `Connection`. The listener is passed a `ConnectionStateChange` object that contains the current state, previous state, the event, and an optional reason for the event or state change. For the `update` event, the current and previous states will be the same.
If an exception is thrown in the listener and bubbles up to the event emitter, it will be caught and logged at `error` level, so as not to affect other listeners for the same event.
### Javascript
```
realtime.connection.on('connected', (stateChange) => {
console.log('Connected to Ably');
});
realtime.connection.on(['disconnected', 'suspended'], (stateChange) => {
console.log('Connection lost:', stateChange.reason);
});
```
### Parameters
The `on()` method takes the following parameters:
| Parameter | Required | Description | Type |
| --- | --- | --- | --- |
| event | Optional | A single connection event to listen for. | |
| events | Optional | An array of connection events to listen for. | [] |
| listener | Required | A function notified for each matching event. If neither `event` nor `events` is supplied, it fires for every event. | |
| Value | Description |
| --- | --- |
| initialized | The connection object has been initialized but no connection has yet been attempted. |
| connecting | A connection attempt has been initiated. |
| connected | A connection has been established. |
| disconnected | The connection has been temporarily lost. |
| suspended | The connection has been lost for an extended period. |
| closing | An explicit close request has been sent. |
| closed | The connection has been explicitly closed. |
| failed | The connection failed and will not be reattempted. |
| update | An update to the connection has occurred (typically a re-auth or capability update) while the connection state remains `connected`. |
| Parameter | Description | Type |
| --- | --- | --- |
| stateChange | The connection state change that occurred. | |
| Property | Description | Type |
| --- | --- | --- |
| current | The new state. | |
| previous | The previous state. For the `update` event, this will be equal to the `current` state. | |
| event | The event that triggered this state change. | |
| reason | An `ErrorInfo` containing any information relating to the transition. | [ErrorInfo](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#errorinfo) or Undefined |
| retryIn | Duration in milliseconds upon which the SDK will retry a connection, where applicable. | Number or Undefined |
## Register a one-time state change listener
`connection.once(event: ConnectionEvent, listener: connectionEventCallback): void`
Register the given listener for a single occurrence of the specified `ConnectionEvent` on the `Connection`. Once the listener has been called, it is removed as a registered listener and will not be called again.
`connection.once(listener: connectionEventCallback): void`
Register the given listener for a single occurrence of any `ConnectionEvent` on the `Connection`.
`connection.once(event: ConnectionEvent): Promise`
Returns a promise that is fulfilled with the next `ConnectionStateChange` for the specified event. This is the preferred way to await a specific connection state from async code.
`connection.once(): Promise`
Returns a promise that is fulfilled with the next `ConnectionStateChange`, regardless of the event type.
### Javascript
```
await realtime.connection.once('connected');
console.log('Connected');
```
### Parameters
The `once()` method takes the following parameters:
| Parameter | Required | Description | Type |
| --- | --- | --- | --- |
| event | Optional | The connection event to listen for. If omitted, the listener fires for any event. | |
| listener | Optional | A function notified for the next occurrence of the matching event. Omit to return a promise instead. | |
### Returns
The callback-based overloads return `void`.
The promise-based overloads return `Promise`. The promise is fulfilled with a `ConnectionStateChange` object the next time a matching event occurs, or rejected with an [`ErrorInfo`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#errorinfo) object if the connection enters a state from which the event cannot occur.
## Remove a state change listener
`connection.off(event: ConnectionEvent, listener: connectionEventCallback): void`
Remove the given listener for the specified `ConnectionEvent`.
`connection.off(listener: connectionEventCallback): void`
Remove the given listener for all `ConnectionEvent`s.
`connection.off(): void`
Removes all listeners, including those registered with and without specific events.
### Javascript
```
const listener = (stateChange) => console.log(stateChange.current);
realtime.connection.on('connected', listener);
// Remove the specific listener for 'connected'
realtime.connection.off('connected', listener);
// Remove all listeners
realtime.connection.off();
```
### Parameters
The `off()` method takes the following parameters:
| Parameter | Required | Description | Type |
| --- | --- | --- | --- |
| event | Optional | The connection event to unsubscribe from. If omitted, the listener is removed from all events. | |
| listener | Optional | The listener function to remove. If omitted, all listeners are removed. | |
## Ping the Ably service
`connection.ping(): Promise`
When connected, sends a heartbeat ping to the Ably server and returns the round-trip time in milliseconds when a heartbeat ping response is received from the server. Useful for measuring the true round-trip latency to the connected Ably server.
### Javascript
```
const latency = await realtime.connection.ping();
console.log(`Latency: ${latency}ms`);
```
### Returns
`Promise`
Returns a promise. The promise is fulfilled with a number representing the time in milliseconds for the heartbeat ping request to be echoed, or rejected with an [`ErrorInfo`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#errorinfo) object that details the reason why it was rejected.
## Get registered listeners
`connection.listeners(eventName?: ConnectionEvent): null | connectionEventCallback[]`
Returns the listeners registered for the specified `ConnectionEvent`. If `eventName` is omitted, returns all registered listeners.
### Parameters
The `listeners()` method takes the following parameters:
| Parameter | Required | Description | Type |
| --- | --- | --- | --- |
| eventName | Optional | The connection event to filter listeners by. | |
### Returns
`null | connectionEventCallback[]`
Returns an array of registered listener functions, or `null` if no listeners are registered for the specified event.
## Wait for a connection state
`connection.whenState(targetState: ConnectionState): Promise`
If the connection is already in the given state, returns a promise which immediately resolves to `null`. Otherwise calls [`once()`](#once) to return a promise which resolves the next time the connection transitions to the given state.
### Javascript
```
await realtime.connection.whenState('connected');
```
### Parameters
The `whenState()` method takes the following parameters:
| Parameter | Required | Description | Type |
| --- | --- | --- | --- |
| targetState | Required | The connection state to wait for. | |
### Returns
`Promise`
Returns a promise. If the connection is already in the given state, the promise immediately resolves to `null`. Otherwise it resolves with a `ConnectionStateChange` the next time the connection transitions to that state.
## Create a connection recovery key
`connection.createRecoveryKey(): null | string`
Generates a string that can be used by another client to recover the current connection's state using [`clientOptions.recover`](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md#constructor-params), as described in the [connection state recovery options](https://ably.com/docs/connect/states.md#connection-state-recover-options).
### Javascript
```
const recoveryKey = realtime.connection.createRecoveryKey();
```
### Returns
`null | string`
Returns a recovery key string, or `null` if a recovery key cannot be generated (for example, if the connection has never been connected).
## Related Topics
- [Realtime client](https://ably.com/docs/pub-sub/api/javascript/realtime/realtime-client.md): API reference for the Realtime client class in the Ably Pub/Sub JavaScript Realtime SDK.
- [Auth](https://ably.com/docs/pub-sub/api/javascript/realtime/auth.md): API reference for the Authentication (Auth) interface in the Ably Pub/Sub JavaScript Realtime SDK.
- [Crypto](https://ably.com/docs/pub-sub/api/javascript/realtime/crypto.md): API reference for the Encryption (Crypto) utility in the Ably Pub/Sub JavaScript Realtime SDK.
## Documentation Index
To discover additional Ably documentation:
1. Fetch [llms.txt](https://ably.com/llms.txt) for the canonical list of available pages.
2. Identify relevant URLs from that index.
3. Fetch target pages as needed.
Avoid using assumed or outdated documentation paths.