What are server-sent events?
By FrontendPro Editorial Team Updated 8/8/2026
Answer
Server-sent events (SSE) is a standard that allows a web page to receive automatic updates from a server via an HTTP connection. Server-sent events are used with EventSource instances that open a connection with a server and allow the client to receive events from the server. Connections created by server-sent events are persistent (similar to the WebSockets), however there are a few differences:
| Property | WebSocket | EventSource |
|---|---|---|
| Direction | Bi-directional – both client and server can exchange messages | Unidirectional – only server sends data |
| Data type | Binary and text data | Only text |
| Protocol | WebSocket protocol (ws://) | Regular HTTP (http://) |
Creating an event source
const eventSource = new EventSource("/sse-stream");
Listening for events
// Fired when the connection is established.
eventSource.addEventListener("open", () => {
console.log("Connection opened");
});
// Fired when a message is received from the server.
eventSource.addEventListener("message", (event) => {
console.log("Received message:", event.data);
});
// Fired when an error occurs.
eventSource.addEventListener("error", (error) => {
console.error("Error occurred:", error);
});
Sending events from server
const express = require("express");
const app = express();
app.get("/sse-stream", (req, res) => {
// `Content-Type` need to be set to `text/event-stream`.
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
// Each message should be prefixed with data.
const sendEvent = (data) => res.write(`data: ${data}\n\n`);
sendEvent("Hello from server");
const intervalId = setInterval(() => sendEvent(new Date().toString()), 1000);
res.on("close", () => {
console.log("Client closed connection");
clearInterval(intervalId);
});
});
app.listen(3000, () => console.log("Server started on port 3000"));
In this example, the server sends a "Hello from server" message initially, and then sends the current date every second. The connection is kept alive until the client closes it.
<br>Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
