Kanbritech Learn logo
HTML Web APIs 45h track

Server-Sent Events API

Name the response media type and message boundary required by an SSE endpoint.

Understand the topic

Server-Sent Events stream updates from a server to the browser using EventSource. This is one-way communication; the client uses ordinary requests for messages back to the server. The endpoint responds with text/event-stream, sends messages separated by blank lines, and keeps the connection available as appropriate. Authentication, disconnects, buffering, and reconnection must be considered.

Worked example

// Browser code; /events must be implemented on the server.
const feed = new EventSource("/events");
feed.onmessage = (event) => console.log("Update:", event.data);
feed.onerror = () => console.log("Stream interrupted; the browser may reconnect.");
// When the feature is no longer needed:
// feed.close();

// Example server response body:
// data: A new HTML lesson is available.
// followed by a blank line

The example requires a real streaming endpoint. It is not enabled automatically by adding EventSource. Close the connection when leaving the relevant view.

Practice

Name the response media type and message boundary required by an SSE endpoint.

Show a suggested answer
Content-Type: text/event-stream
Each event ends with a blank line, for example: data: Ready\n\n

Common mistake

Do not describe SSE as a two-way socket protocol or expect a missing /events route to stream updates.

HTML documentation

Try Coding

Result