> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/ably/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Server-Sent Events (SSE) API

The Ably Server-Sent Events (SSE) API provides a simple way to receive real-time messages over HTTP using the [Server-Sent Events](https://www.w3.org/TR/eventsource/) standard. This is useful for browser clients that support SSE and scenarios where the full Ably client library SDK is not suitable.

## Overview

The SSE API enables you to:

* Receive real-time messages over HTTP
* Subscribe to one or more channels
* Use standard SSE libraries and the browser EventSource API
* Automatically reconnect on connection loss

## When to Use SSE

The SSE API is ideal for:

* Browser applications that need simple real-time updates
* Environments with limited WebSocket support
* Read-only real-time data consumption
* Lightweight integrations

For full bidirectional communication and advanced features, use the [Realtime SDK](/docs/api/realtime-sdk).

## Getting Started

### Basic Usage

Connect to the SSE endpoint and subscribe to a channel:

<Code>
  ```javascript theme={null}
  const eventSource = new EventSource(
    'https://realtime.ably.io/sse?channels=my-channel&v=1.2&key={{API_KEY}}'
  );

  eventSource.onmessage = (event) => {
    const message = JSON.parse(event.data);
    console.log('Message:', message);
  };
  ```

  ```python theme={null}
  import sseclient
  import requests

  url = 'https://realtime.ably.io/sse?channels=my-channel&v=1.2&key={{API_KEY}}'
  response = requests.get(url, stream=True)
  client = sseclient.SSEClient(response)

  for event in client.events():
      message = json.loads(event.data)
      print('Message:', message)
  ```
</Code>

## Endpoint

The SSE endpoint is:

<Code>
  ```text theme={null}
  GET https://realtime.ably.io/sse
  ```
</Code>

### Parameters

<ParamField path="channels" type="string" required>
  One or more channel names, separated by commas. Non-URL-safe characters should be URL-encoded.

  Example: `channels=channel1,channel2`
</ParamField>

<ParamField path="v" type="string" required>
  API version. Use `v=1.2` for the current version.
</ParamField>

<ParamField path="key" type="string">
  Your Ably API key for Basic authentication.
</ParamField>

<ParamField path="accessToken" type="string">
  An Ably auth token for Token authentication.
</ParamField>

<ParamField path="lastEvent" type="string">
  Event ID to resume from when reconnecting.
</ParamField>

<ParamField path="rewind" type="integer">
  Number of recent messages to retrieve on connection. Maximum 100.

  Example: `rewind=10` retrieves the last 10 messages.
</ParamField>

<ParamField path="enveloped" type="boolean" default="true">
  If `true`, message data is wrapped in a Message object. If `false`, returns raw message payload.
</ParamField>

<ParamField path="heartbeats" type="boolean" default="false">
  If `true`, sends explicit heartbeat events. If `false`, uses newlines as keepalive.
</ParamField>

<ParamField path="separator" type="string">
  Custom separator for channel names (useful when channel names contain commas).

  Example: `separator=|&channels=ch1|ch2`
</ParamField>

## Message Format

Messages are delivered as SSE events:

<Code>
  ```text theme={null}
  id: cbfKayrzgAXDWM:1556806691343-0
  event: message
  data: {
    "id":"YqigX7VFsR:0:0",
    "name":"event-name",
    "timestamp":1556806691341,
    "channel":"my-channel",
    "data":"{\"foo\":1}"
  }
  ```
</Code>

### Event Types

The SSE API sends the following event types:

<ResponseField name="message" type="event">
  A message published to the channel.
</ResponseField>

<ResponseField name="presence" type="event">
  A presence event on the channel.
</ResponseField>

<ResponseField name="error" type="event">
  An error occurred (for example, token expired).
</ResponseField>

<ResponseField name="heartbeat" type="event">
  Keepalive heartbeat (when `heartbeats=true`).
</ResponseField>

## Connection Management

### Automatic Reconnection

The browser EventSource API automatically reconnects on connection loss. Use the `lastEvent` parameter to resume from the last received message:

<Code>
  ```javascript theme={null}
  const eventSource = new EventSource(
    'https://realtime.ably.io/sse?channels=my-channel&v=1.2&key={{API_KEY}}'
  );

  let lastEventId;

  eventSource.onmessage = (event) => {
    lastEventId = event.lastEventId;
    // Process message
  };

  eventSource.onerror = () => {
    eventSource.close();
    // Reconnect with lastEventId
    const newSource = new EventSource(
      `https://realtime.ably.io/sse?channels=my-channel&v=1.2&key={{API_KEY}}&lastEvent=${lastEventId}`
    );
  };
  ```
</Code>

### Keepalive

The SSE connection sends keepalive packets to maintain the connection:

* By default, newline characters (`\n`) are sent
* With `heartbeats=true`, explicit heartbeat events are sent

## Authentication

### Basic Authentication

Use your API key in the URL:

<Code>
  ```javascript theme={null}
  const eventSource = new EventSource(
    'https://realtime.ably.io/sse?channels=my-channel&v=1.2&key={{API_KEY}}'
  );
  ```
</Code>

### Token Authentication

Use an Ably Token:

<Code>
  ```javascript theme={null}
  const eventSource = new EventSource(
    'https://realtime.ably.io/sse?channels=my-channel&v=1.2&accessToken={{TOKEN}}'
  );
  ```
</Code>

## Examples

### Subscribe to Multiple Channels

<Code>
  ```javascript theme={null}
  const eventSource = new EventSource(
    'https://realtime.ably.io/sse?channels=channel1,channel2,channel3&v=1.2&key={{API_KEY}}'
  );

  eventSource.onmessage = (event) => {
    const message = JSON.parse(event.data);
    console.log(`Channel: ${message.channel}, Data: ${message.data}`);
  };
  ```
</Code>

### Retrieve Recent Messages

<Code>
  ```javascript theme={null}
  const eventSource = new EventSource(
    'https://realtime.ably.io/sse?channels=my-channel&v=1.2&key={{API_KEY}}&rewind=10'
  );

  eventSource.onmessage = (event) => {
    const message = JSON.parse(event.data);
    console.log('Message:', message);
  };
  ```
</Code>

### Handle Errors

<Code>
  ```javascript theme={null}
  const eventSource = new EventSource(
    'https://realtime.ably.io/sse?channels=my-channel&v=1.2&key={{API_KEY}}'
  );

  eventSource.addEventListener('error', (event) => {
    if (event.data) {
      const error = JSON.parse(event.data);
      console.error('Error:', error.message);
    }
  });
  ```
</Code>

## Limitations

### Read-Only

The SSE API is read-only. To publish messages, use:

* [REST API](/docs/api/rest-api)
* [REST SDK](/docs/api/rest-sdk)
* [Realtime SDK](/docs/api/realtime-sdk)

### No Presence

While you can receive presence events, you cannot enter presence using the SSE API. Use the [Realtime SDK](/docs/api/realtime-sdk) for full presence functionality.

### Connection Limits

Browsers typically limit concurrent SSE connections to 6 per domain.

## Related Resources

* [Realtime SDK](/docs/api/realtime-sdk)
* [REST API](/docs/api/rest-api)
* [EventSource API (MDN)](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
* [Server-Sent Events Specification](https://www.w3.org/TR/eventsource/)
