API v 1.2
JavaScript

SSE and Raw HTTP Streaming API

The Ably SSE and raw HTTP streaming API provides a way to get a realtime stream of events from Ably in circumstances where using a full Ably Realtime client library, or even an MQTT library, is impractical.

HTTP streaming allows for a request from a client to be held by a server, allowing it to push data to the client without further requests. This, much like WebSockets, help avoid the overhead involved in normal HTTP requests. Server-sent events (SSE) provide a thin layer on top of HTTP streaming. A common use of SSE is through the use of the EventSource API in all modern web browsers.

It is subscribe-only: you can not interact with the channel, including to publish, enter presence, query the presence set, attach and detach from channels (without closing and re-opening the stream), or anything else.

Customers who do not want to use a client library on platforms that support SSE, and only require simple subscribe-only streams, may choose to use SSE because it’s an open standard, simple, and requires no SDKs on the client-side. HTTP Streaming may be considered on platforms without an SSE client. However, where possible, we strongly recommend the use of one of our Realtime client libraries, which provide more features and higher reliability, and the full use of our normal realtime messaging API.

SSE is incredibly simple to get started with. The code sample below provides an example of how to use it with Ably.

var apiKey ='<loading API key, please wait>'; var url ='https://realtime.ably.io/event-stream?channels=myChannel&v=1.2&key=' + apiKey; var eventSource = new EventSource(url); eventSource.onmessage = function(event) { var message = JSON.parse(event.data); console.log('Message: ' + message.name + ' - ' + message.data); };
Demo Only
Copied!

It is possible to use either basic auth (with an API key) or token auth (using a token issued from your server) with SSE. We recommend token auth on the client side for security reasons, so you have control over who can connect. Basic auth, while lacking this control, is simpler (it doesn’t require you to run an auth server), and you don’t have to worry about the client obtaining a new token when the old one expires.

If using basic auth, you can use a querystring parameter of key or an Authorization: Basic <base64-encoded key> header. If using token auth, you can use an accessToken querystring parameter or an Authorization: Bearer <base64-encoded token> header. See REST API authentication for more information.

Connection state is only retained for two minutes. See Connection state explained for full documentation.

The SSE protocol and the EventSource API are designed so that a dropped connection is resumed transparently; the client implementation will reconnect and supply a lastEventId param that ensures that the resuming connection delivers any events that have arisen since the connection was dropped. Ably uses this mechanism to reattach all channels in a new connection to the exact point that had been reached in the prior connection.

When a token expires the connection will end. However, the default EventSource behaviour of automated reconnection will not work, because the (expired) credentials are part of the connection URL. What is needed is for a new connection to be established, with an updated accessToken. The question then arises as to how to do that with continuity – that is, how to establish a new connection but supply the correct lastEventId so that the new connection resumes from the point that the prior connection became disconnected.

Implementing transparent connection resumes when tokens need to be renewed requires a few additional steps – detecting token expiry and resuming the connection from the point of the last delivered message using the lastEventId attribute:

When a connection is closed as a result of any error (that is, it’s not just a dropped connection), then the error event will occur on the EventSource instance, and the data attribute of the event will contain an Ably error body with the information about the nature of error. In the case of a token error – that is an error arising from a problem with the auth token – the code in the error body will indicate that. Token errors have a code in the range 40140 <= code < 40150. In such cases, the authentication can be retried with a new accessToken.

In the future we plan to send an event on the connection that indicates that the token will expire imminently, which will allow a new connection to be established prior to the closure of the previous connection.

Each message received will have a lastEventId attribute containing the last id of any message received on the connection. When constructing a new connection, this value can be specified as a lastEvent param in the URL.

Here’s example of implementing message continuity with Token Auth:

let lastEvent; const connectToAbly = () => { // obtain a token const token = <GET-NEW-ABLY-AUTH-TOKEN> // establish a connection with that token const lastEventParam = lastEvent ? ('&lastEvent=' + lastEvent) : ''; eventSource = new EventSource(`https://realtime.ably.io/sse?v=1.1&accessToken=${token}&channels=${channel}${lastEventParam}`); // handle incoming messages eventSource.onmessage = msg => { lastEvent = msg.lastEventId; // ... normal message processing } // handle connection errors eventSource.onerror = msg => { const err = JSON.parse(msg.data); const isTokenErr = err.code >= 40140 && err.code < 40150; if(isTokenErr) { eventSource.close(); connectToAbly(); } else { // ... handle other types of error -- for example, retry on 5xxxx, close on 4xxxx } } } connectToAbly();
Copied!

An important thing to note here is that the EventSource API tries to auto-reconnect and re-subscribe to the SSE endpoint when any error occurs, even the token expiry error like in this case. This means that upon manually re-subscribing to the SSE endpoint with a new token, there will be two active subscriptions to the endpoint – one with the old token which would continue to throw an error due to expired credentials and another with the new token. Hence, it is important to close the previous EventSource subscription using eventSource.close() before re-subscribing with the new token as shown in the snippet above.

You can take a look at a demo app and a complete code example for implementing message continuity in an SSE subscription when using token auth.

View the Server-Sent Events API Reference.