
Modern web applications often need to display information as soon as it becomes available. Examples include live notifications, order updates, stock prices, monitoring dashboards, news feeds and delivery tracking.
Traditional web applications frequently rely on repeated requests to check whether new information is available. This approach is called polling. Although it works, repeated requests can create unnecessary network traffic and server workload.
Server-Sent Events (SSE) provide a simpler way to deliver real-time updates from a server to a browser. Instead of repeatedly requesting new information, the browser establishes an HTTP connection that remains open while the server sends events whenever updates are available.
SSE is particularly useful when information needs to travel in one direction: from the server to the client.
This guide explains how Server-Sent Events work, their architecture, EventSource API, implementation, advantages, limitations, security considerations and practical applications.
Server-Sent Events is a web technology that allows a server to send continuous updates to a browser over a single HTTP connection.
It uses the text/event-stream content type to deliver events in a structured text format.
The browser provides a built-in JavaScript interface called EventSource, which connects to an SSE endpoint and listens for incoming events.
For example, imagine an e-commerce website where a customer places an order. Instead of refreshing the page repeatedly, the application can use SSE to send updates such as:
Order confirmed.
Payment completed.
Package dispatched.
Package out for delivery.
Order delivered.
Whenever the server receives a relevant update, it can send an event to the connected browser.
One-way communication: Data travels from the server to the browser through the SSE connection. The browser sends separate HTTP requests when it needs to communicate with the server.
HTTP-based: SSE uses HTTP, making it compatible with many existing web infrastructure components.
Persistent connection: The connection remains open so that the server can send multiple updates without establishing a new connection for every event.
Automatic reconnection: The browser's EventSource implementation can attempt to reconnect when a connection is interrupted.
Event-based delivery: The server can send messages containing event names, IDs and data.
SSE follows a straightforward communication process between the browser and the server.
The browser creates an EventSource object using the URL of an SSE endpoint.
const events = new EventSource("/events");
The browser sends an HTTP request to the server and indicates that it can accept an event stream.
The server checks the request and responds with the appropriate headers.
The most important response header is:
Content-Type: text/event-stream
The server should also configure the response so that intermediate infrastructure does not unnecessarily buffer the stream.
After establishing the connection, the server sends events whenever relevant information becomes available.
A simple event looks like this:
data: Welcome to the live notification system
Each event ends with a blank line. This tells the browser that the event is complete.
The EventSource object receives the event and triggers its message event handler.
events.onmessage = (event) => {
console.log(event.data);
};
The application can then update the interface without refreshing the page.
The server can continue sending events through the same connection.
If the connection is interrupted, the browser can attempt to reconnect automatically unless the application closes the EventSource object.
Server-Sent Events use a simple text-based format. Each event can contain one or more fields.
The data field contains the information sent to the browser.
data: Your order has been confirmed
The browser receives the content through event.data.
The event field specifies a custom event name.
event: order-update
data: Your package has been dispatched
The browser can listen for this named event using addEventListener().
The id field assigns an identifier to an event.
id: 105
data: New notification received
When a connection is re-established, the browser can send the last received event ID using the Last-Event-ID request header.
The server can use this information to resume event delivery when it maintains an appropriate event history.
The retry field suggests a reconnection delay in milliseconds.
retry: 3000
data: Connection established
In this example, the browser is instructed to wait approximately three seconds before attempting to reconnect after a connection failure.
A line beginning with a colon is treated as a comment.
: keep-alive
Comments do not generate message events. They can be used as heartbeat data to help prevent idle connections from being closed by intermediate network infrastructure.
The EventSource API is a browser interface that allows JavaScript applications to receive Server-Sent Events.
It manages the connection and provides event handlers for incoming data and connection status.
const source = new EventSource("/events");
This creates a connection to the specified endpoint.
source.onmessage = (event) => {
console.log("Received:", event.data);
};
This handler receives events that do not specify a custom event name.
source.addEventListener("notification", (event) => {
console.log("Notification:", event.data);
});
Custom events allow applications to separate different types of updates.
source.onopen = () => {
console.log("SSE connection opened");
};
source.onerror = () => {
console.log("SSE connection error");
};
These handlers help developers monitor the connection lifecycle.
source.close();
The close() method permanently closes that EventSource instance. The browser will not automatically reconnect that closed instance.
A practical implementation makes it easier to understand how SSE works.
This example uses Node.js and Express to create an endpoint that sends periodic updates to connected browsers.
Create a new project directory and initialise Node.js.
mkdir sse-demo
cd sse-demo
npm init -y
npm install express
Create the following files:
server.js
index.html
Add the following code to server.js:
const express = require("express");
const app = express();
const PORT = 3000;
app.use(express.static("public"));
const clients = new Set();
app.get("/events", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.flushHeaders?.();
const client = { response: res };
clients.add(client);
res.write("retry: 3000\n\n");
res.write(
`event: connected\ndata: ${JSON.stringify({
message: "Connected to live updates"
})}\n\n`
);
req.on("close", () => {
clients.delete(client);
});
});
function broadcastEvent(eventName, payload) {
const message = JSON.stringify(payload);
for (const client of clients) {
try {
client.response.write(
`event: ${eventName}\n`
);
client.response.write(
`data: ${message}\n\n`
);
} catch (error) {
clients.delete(client);
}
}
}
setInterval(() => {
broadcastEvent("notification", {
message: "A new update is available",
timestamp: new Date().toISOString()
});
}, 5000);
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This server:
Creates an SSE endpoint at /events.
Sets the event-stream response headers.
Maintains a collection of connected clients.
Sends a notification every five seconds.
Removes disconnected clients from the collection.
This is a learning example. A production implementation also needs authentication, connection limits, heartbeat handling, graceful shutdown and infrastructure-specific configuration. The in-memory client collection works only within one server process.
Create a public directory and add index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSE Live Notifications</title>
</head>
<body>
<h1>Live Notifications</h1>
<p id="status">Connecting...</p>
<ul id="notifications"></ul>
<script>
const status = document.getElementById("status");
const notifications = document.getElementById("notifications");
const source = new EventSource("/events");
source.addEventListener("connected", (event) => {
const data = JSON.parse(event.data);
status.textContent = data.message;
});
source.addEventListener("notification", (event) => {
const data = JSON.parse(event.data);
const item = document.createElement("li");
item.textContent =
`${data.message} - ${data.timestamp}`;
notifications.prepend(item);
});
source.onerror = () => {
status.textContent = "Connection interrupted or reconnecting...";
};
window.addEventListener("beforeunload", () => {
source.close();
});
</script>
</body>
</html>
Start the server:
node server.js
Open the application at:
http://localhost:3000
The browser establishes an SSE connection and displays a new notification every five seconds.
An application may need to deliver different event categories through the same connection.
For example, a dashboard might receive:
notification
order-update
payment-status
system-alert
The server can use the event field to identify each message type.
source.addEventListener("order-update", (event) => {
const order = JSON.parse(event.data);
console.log("Order update:", order);
});
source.addEventListener("system-alert", (event) => {
const alert = JSON.parse(event.data);
console.log("System alert:", alert);
});
This makes event handling more organised and helps developers build interfaces around specific update categories.
One useful feature of SSE is its automatic reconnection mechanism.
If the connection is interrupted because of a network problem, the browser can attempt to reconnect after the configured delay.
However, reconnecting does not automatically guarantee that no events will be missed.
The server can assign an ID to every event.
id: 501
event: order-update
data: {"status":"dispatched"}
When the browser reconnects, it can include the last event ID it received in the Last-Event-ID header.
The server can examine this value and send subsequent events from its event history.
For this to work reliably, the application must maintain a replayable event log or another suitable recovery mechanism.
A simple server that only broadcasts new events to currently connected clients cannot recover messages that were sent while a user was disconnected.
Polling is a technique in which a browser sends repeated requests to check whether new information is available.
For example, a browser might request /notifications every five seconds.
With SSE, the browser establishes a persistent connection and the server sends information when updates become available.
SSE can reduce unnecessary requests when updates are irregular. Polling may still be appropriate for simple applications, infrequent updates or environments where persistent connections are difficult to maintain.
SSE and WebSockets are both used for real-time web communication, but they serve different requirements.
Communication direction: SSE is designed for server-to-client communication. WebSockets support two-way communication between the client and server.
Protocol: SSE uses HTTP response streaming. WebSockets begin with an HTTP handshake and then use the WebSocket protocol.
Browser API: SSE uses EventSource, while WebSockets use the WebSocket API.
Message format: SSE uses a text-based event format. WebSockets can carry text and binary messages.
Typical applications: SSE is useful for notifications, live feeds and status updates. WebSockets are suitable for chat systems, multiplayer games and interactive applications requiring continuous two-way messaging.
The best option depends on whether the application needs one-way updates or interactive communication in both directions.
Browsers and infrastructure can impose limits on concurrent connections.
HTTP/1.1 environments may have relatively restrictive per-origin connection limits. HTTP/2 can improve multiplexing, although practical limits still depend on browser and server configuration.
Applications should avoid opening unnecessary EventSource connections.
Some reverse proxies and intermediaries buffer responses.
This can delay events even when the application server sends them immediately.
Developers may need to disable buffering for SSE routes and configure suitable proxy timeouts.
A long-lived connection can be closed by infrastructure that considers it idle.
The server can periodically send comment lines as heartbeat messages.
: heartbeat
The heartbeat interval should be shorter than relevant idle timeouts.
Each active SSE connection consumes server and network resources.
A production server should monitor:
Active connections
Memory usage
Network bandwidth
Event delivery rates
Disconnected clients
Reconnection frequency
If an application runs across multiple server instances, a client connected to one instance may not receive events generated by another instance.
A shared messaging system or event broker can distribute updates between server processes.
Examples include Redis Pub/Sub, Apache Kafka and other message-broker technologies. The appropriate choice depends on delivery guarantees, ordering, retention and scale requirements.
SSE connections may carry user-specific or business-sensitive information. Security must be considered from the beginning.
The server should verify the user's identity before establishing a connection.
Browser EventSource supports credential mode through its options, which can be useful for cookie-based authentication.
const source = new EventSource("/events", {
withCredentials: true
});
The server must still validate the session and ensure that the user is authorised to receive the requested events.
Authentication identifies the user, while authorisation determines which events that user can access.
For example, one customer should not receive another customer's order updates.
The server should associate each connection with an authorised user or tenant and filter outgoing events accordingly.
Use HTTPS in production to protect event data while it travels between the browser and server.
If an SSE endpoint is accessed from another origin, configure CORS carefully.
When credentialed requests are used, the server must specify an appropriate allowed origin and allow credentials. A wildcard origin is not valid for credentialed CORS responses.
Long-lived connections need proper session-expiration handling.
The server should close or revalidate connections when authentication expires or user permissions change.
Send only the information required by the browser. Do not expose passwords, secret keys, internal server details or unnecessary personal data in event messages.
Web applications can deliver notifications about new messages, account activity, task completion and system updates.
Customers can receive updates when an order is confirmed, packed, dispatched or delivered.
Financial dashboards can display price changes and market information as the server receives new data.
System monitoring applications can stream metrics, alerts and infrastructure status changes.
News platforms can deliver breaking headlines and newly published content without requiring users to refresh the page.
Booking platforms can send updates about appointment status, reservation changes and availability notifications.
Applications that process uploads, reports or background jobs can stream progress updates to the browser.
Practical projects help developers understand persistent connections, event delivery and browser-side updates.
Build a notification application using Node.js, Express and EventSource.
Include notification categories, timestamps, connection status and a way to mark notifications as read.
Create a simple shopping application that sends order-status updates to customers.
Use separate event types for payment, packaging, dispatch and delivery.
Build a dashboard that receives CPU usage, memory statistics and service-status updates.
Use simulated metrics initially and connect to a monitoring system later.
Create a file-processing application that sends progress updates to the browser.
Display the percentage completed and final processing status.
Develop a page that receives newly published headlines through an SSE endpoint.
Add categories and timestamps to organise incoming updates.
Developers should understand several web technologies before implementing SSE in production.
JavaScript: Learn event listeners, callbacks, asynchronous programming and browser APIs.
HTML and CSS: Understand how to create interfaces that display incoming updates.
HTTP fundamentals: Learn request and response headers, status codes, persistent connections and content types.
Backend development: Practise building server endpoints using Node.js, Express or another backend framework.
Networking: Understand connection management, proxies, timeouts and HTTP/2.
Authentication and security: Learn session handling, CORS, HTTPS and access control.
Database fundamentals: Understand how applications retrieve and prepare data before sending events.
System monitoring: Learn how to measure active connections, event delivery and resource consumption.
Server-Sent Events is a useful skill for developers working on real-time web applications.
It can contribute to knowledge required in roles such as:
Frontend Developer: Builds browser interfaces that receive and display live updates.
Backend Developer: Creates event-stream endpoints and manages server-side connections.
Full Stack Developer: Integrates frontend event handling with backend event delivery.
Real-Time Application Developer: Develops notification systems, monitoring interfaces and live data applications.
Software Engineer: Designs communication systems for scalable web applications.
Platform Engineer: Works on infrastructure that supports persistent connections and event distribution.
SSE is usually one part of a broader web-development skill set rather than a separate career specialisation.
Follow a practical learning path:
Understand HTTP requests and responses.
Learn JavaScript event listeners and asynchronous programming.
Study the EventSource API.
Understand the text/event-stream format.
Build a basic SSE server using Node.js and Express.
Create a browser interface that receives custom events.
Practise automatic reconnection and event IDs.
Learn how authentication and CORS work with SSE.
Experiment with reverse proxies and HTTP/2.
Build a real-time dashboard or notification application.
Start with a small application before exploring large-scale event distribution.
Developers interested in real-time web applications can explore additional learning material through these EasyShiksha resources:
Online Courses – Explore learning opportunities across technology and development.
Search Courses – Find relevant programming and software-development learning resources.
Web Development – Explore web-development learning topics and related skills.
Server-Sent Events provide a practical method for delivering real-time updates from servers to browsers through HTTP. With a persistent connection, a simple event format and the built-in EventSource API, developers can build live notifications, dashboards, tracking systems and other event-driven interfaces without implementing a full two-way communication protocol.
SSE is not a replacement for every real-time technology. It is most suitable when the server needs to continuously send information to the browser while client-to-server communication can happen through ordinary HTTP requests.
Understanding SSE helps developers choose the right communication approach and build responsive applications with efficient event delivery.
SSE stands for Server-Sent Events. It is a web technology that allows servers to send real-time event updates to browsers over an HTTP connection.
SSE is a web platform technology built around an HTTP streaming response and a defined event-stream format. It uses the text/event-stream media type and the browser's EventSource API.
EventSource is a browser JavaScript interface used to connect to an SSE endpoint. It receives server events and provides handlers for messages, connection opening and errors.
No. SSE is designed for one-way server-to-client communication. The browser can send information separately through HTTP requests, but those requests are not part of the SSE event stream.
The server sends the Content-Type: text/event-stream response header to identify an SSE stream.
Yes. The browser's EventSource implementation can automatically attempt to reconnect when a connection is interrupted. The server can suggest a retry delay using the retry field.
It is a request header that the browser can send when reconnecting to an SSE endpoint. It identifies the last event received, allowing the server to resume delivery if it maintains an event history.
Yes. SSE itself uses a text-based format, but the data field can contain JSON strings. The browser can parse them using JSON.parse().
Polling sends repeated HTTP requests to check for updates. SSE maintains a connection through which the server sends updates when they become available. SSE can reduce unnecessary repeated requests for continuously updated information.
SSE supports one-way server-to-client event streaming over HTTP. WebSockets provide two-way communication between the client and server. SSE is useful for notifications and live feeds, while WebSockets are useful for interactive applications such as chat systems.
Yes. Node.js can create SSE endpoints using its built-in HTTP capabilities or frameworks such as Express. The server writes correctly formatted events to the open response.
Yes. React applications can create an EventSource connection inside a component effect, update component state when events arrive and close the connection during cleanup.
Yes. SSE can operate over HTTP/2. HTTP/2 multiplexing can help applications manage multiple streams more efficiently than traditional HTTP/1.1 connection arrangements.
The SSE event format is text-based. Binary information must be encoded into text, such as Base64, or delivered through a separate HTTP endpoint.
SSE can deliver incoming chat messages from the server to the browser, while the browser sends messages through ordinary HTTP requests. However, WebSockets are often more suitable when frequent two-way communication is central to the application.
Use HTTPS, authenticate connections, verify user permissions, configure CORS correctly and ensure that event streams expose only authorised information.
Yes. Multiple browsers can connect to the same endpoint. The server must manage each connection and ensure that each user receives only the events they are authorised to access.
Existing connections are interrupted. Browsers may attempt to reconnect, but event recovery requires the application to maintain event history or another mechanism for replaying missed events.
Yes, when the server infrastructure is designed for persistent connections and high event volumes. Large deployments need connection management, load balancing, shared event distribution and monitoring.
Choose SSE when the application primarily needs server-to-browser updates, such as notifications, live dashboards, order tracking, news feeds and background-task progress. Choose another communication approach when continuous two-way messaging or binary streaming is required.
More News Click here
Discover thousands of colleges and courses, enhance skills with online courses and internships, explore career alternatives, and stay updated with the latest educational news..
Gain high-quality, filtered student leads, prominent homepage ads, top search ranking, and a separate website. Let us actively enhance your brand awareness.