Server-driven HTTP lets a server send information without a new client request for every update. Server-Sent Events (SSE) is a simple standardized option for one-way server-to-browser updates.
Server-Sent Events #
An SSE client makes a normal GET request with an Accept: text/event-stream header. The server replies with 200 OK,
Content-Type: text/event-stream, and keeps the response open while sending
UTF-8 event fields separated by a blank line:
event: order-updated
id: 42
data: {"status":"paid"}In browsers, EventSource reconnects automatically. The server can send
retry: to suggest a reconnection delay, and the browser sends
Last-Event-ID after a reconnect when an event ID was received. Design the
stream so clients can resume from that ID or refresh a snapshot safely.
SSE is one-way: clients use ordinary HTTP requests for commands. Use WebSocket
when bidirectional low-latency messaging is required. Send periodic comments
such as : keepalive when proxies might close quiet connections, flush each
event, and configure reverse proxies not to buffer the response.
Authenticate the initial request as carefully as any other endpoint. Native
EventSource cannot attach arbitrary authorization headers, so a same-site,
secure cookie session is often preferable to placing bearer credentials in the
URL. Enforce authorization for every subscription and close streams on session
revocation where the application requires it.
Comments
Read or comment on GitHub (sign-in required to comment)