Course contentsShow
← Node.js
Lesson 588 of 1,9806. Networking and HTTP FundamentalsFree lesson

Server-Sent Events Implementation

Establish long-lived persistent connections to push real-time updates from the server to clients.

In this lesson, you will learn how to maintain a persistent, one-way communication channel from your Node.js server to a client using Server-Sent Events (SSE).

The Concept of a Persistent Stream

Normally, an HTTP request follows a "request-response" cycle: the client asks, the server answers, and the connection closes. SSE changes this by keeping the connection open. By setting specific HTTP headers, the server signals that it will continue to send data over time rather than closing the socket immediately. This is perfect for real-time updates like stock tickers or live notifications, as it works over standard HTTP and is simpler to implement than WebSockets.

Implementing the Handshake

To initiate an SSE stream in Node.js, you must configure the response headers to keep the connection alive. The Content-Type must be set to text/event-stream, the Cache-Control to no-cache, and the Connection to keep-alive.

http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  // Push updates every 2 seconds
  const interval = setInterval(() => {
    res.write(`data: The current time is ${new Date().toISOString()}\n\n`);
  }, 2000);

  // Clean up when the client disconnects
  req.on('close', () => clearInterval(interval));
}).listen(3000);

The Data Format

The browser expects the data to follow a specific format: a line starting with data: , followed by your payload, and ending with two newline characters (\n\n). These double newlines act as the delimiter, telling the browser that a single "event" has finished and should be dispatched to the client-side EventSource API.

Because this is a persistent connection, it consumes a file descriptor on your server. When managing many clients, ensure your server is optimized for high-traffic concurrency, keeping in mind the memory management and network latency techniques we’ve discussed in previous lessons to ensure the stream remains stable.

Key Takeaway: Server-Sent Events turn a standard HTTP request into a long-lived, unidirectional data stream by keeping the connection open and pushing formatted text messages to the client.