Getting started
Server-sent events (SSE) is a standardised protocol that allows web-servers to push data (characterized as events) to a client without the client having to request it immediately before.
Using SSE can allow for significant savings in bandwidth and battery life on portable devices and will work with your existing infrastructure as it operates directly over the HTTP protocol without the need for the connection upgrade that WebSockets and HTTP/2 do (but can also be used with HTTP/2!).
Compared to WebSockets it has comparable performance and bandwidth usage, especially over HTTP/2, and natively includes event ID generation and automatic reconnection when clients are disconnected.
- Comparison: Server-sent Events vs WebSockets vs Polling
- WHATWG standards section for server-sent events
- MDN guide to server-sent events
- Can I use… Server-sent events
How does it work?
Section titled “How does it work?”SSE works by a client connecting to a server using the EventSource interface. The server then indicates in its response headers that it will send back data in a stream of events and keeps the connection open indefinitely until it is closed by the client. From this point the server is free to continuously write data to the open connection and the EventSource will emit events with the sent data.
- Client makes a request to the server using EventSource.
- Server responds with the
Content-Type
header set totext/event-stream
. - Client emits the
open
event and is ready to receive data. - Server continually writes text data to the open connection.
- Client receives data and emits events on the
EventSource
instance. - Client terminates connection by calling the
close
method.
The technology can be used for things such as live notifications, news tickers, chat rooms, shout-boxes, event logs, progress bars, etc.
Install
Section titled “Install”Better SSE is shipped as a package on npm and the JSR. You can install it with any package manager.
npm install better-sse
yarn add better-sse
pnpm add better-sse
bun add better-sse
deno install jsr:@mwid/better-sse
TypeScript types are included in the package distribution. No need to install from DefinitelyTyped for TypeScript users!
Create a session
Section titled “Create a session”Sessions simply represent an open connection between a client and the server. The client will first make a request to the server and the server will open a session that it will push data to the client with.
First import the module:
import { createSession } from "better-sse"
const { createSession } = require("better-sse")
Then create a session when the client makes a request on the specified route (GET /sse
in this case):
app.get("/sse", async (req, res) => { const session = await createSession(req, res)})
app.get("/sse", (c) => createResponse(c.req.raw, (session) => { // ... }))
Now that we have an active session we can use it to push an event to the client:
session.push("Hello world!", "ping")
This will push the string Hello world!
to the client as an event named ping
(defaults to message
if no name is given.)
Connect from the client
Section titled “Connect from the client”From your client-side code you can now connect to the server at the defined path.
First we open a connection to the server to begin receiving events:
const eventSource = new EventSource("/sse")
Then we can attach an event listener to listen for the event our server is going to send:
eventSource.addEventListener("ping", (event) => { console.log(`${event.type} | ${event.data}`)})
If you check your browser console you will now see ping | "Hello world!"
logged to the console. Easy!
You can find a reference to the received event object interface on the MessageEvent
page on MDN.