Published on

Server-Sent Events: How to Build Real-Time Apps in 10 Minutes

Server-Sent Events (SSE) is a web technology that allows a server to push real-time updates to a web browser over a single, long-lived HTTP connection. Unlike traditional web requests where the client must constantly ask for new data, SSE enables the server to send data automatically the moment it becomes available. You can implement a basic functional SSE stream in under 10 minutes using modern frameworks like Next.js 15 or Node.js 24.

Why should you choose Server-Sent Events over other methods?

Standard HTTP requests follow a "pull" model where your browser asks for information and the server responds. This is inefficient for real-time features like live sports scores or AI chat interfaces because the browser doesn't know exactly when new data exists.

SSE changes this by establishing a "push" model. Once the connection is open, the server keeps it active and sends small packets of data whenever necessary.

In our experience, SSE is often the superior choice for AI applications because it is much simpler to implement than WebSockets. While WebSockets allow two-way communication, SSE is specialized for one-way data flow from the server to the user, which is exactly what you need for streaming text from models like Claude Sonnet 4.

Modern web standards have also improved how SSE performs. By 2026, most browsers and servers utilize HTTP/3, which uses multiplexing (a method of sending multiple signals over one connection) to bypass the old limit of six concurrent connections per domain.

What is the difference between SSE and WebSockets?

WebSockets (a technology for full-duplex, two-way communication) are often the first thing developers think of for real-time apps. However, WebSockets require a different protocol than standard web traffic, which can lead to issues with firewalls or corporate proxies.

SSE works entirely over standard HTTP (Hypertext Transfer Protocol). This means it works out of the box with almost any web server and doesn't require complex handshaking or custom security setups.

If you are building a dashboard, a news feed, or a generative AI interface, SSE is usually the more efficient tool. You only need WebSockets if you are building something highly interactive in both directions, such as a multiplayer game or a collaborative whiteboarding tool.

What do you need to get started?

Before writing any code, ensure your development environment is up to date. Using the latest stable versions ensures you have the best security and performance features available in 2026.

What You'll Need:

  • Node.js 24+: The latest Long Term Support (LTS) version of the JavaScript runtime.
  • A Code Editor: VS Code is the standard choice for most beginners.
  • An AI Assistant: Tools like GPT-5 or Claude Opus 4.5 are excellent at generating the initial boilerplate (starting code) for SSE routes.
  • Basic JavaScript Knowledge: You should understand how variables and functions work.

Step 1: How do you set up a server-side SSE route?

To create an SSE stream, the server must send a specific header (a piece of metadata included in a web request) that tells the browser not to close the connection. This header is Content-Type: text/event-stream.

Create a file named server.js and add the following code using Node.js 24:

import http from 'node:http';

// Create a server that listens for requests
http.createServer((req, res) => {
  // Set headers to keep the connection open for SSE
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
  });

  // Send a message every 3 seconds
  const interval = setInterval(() => {
    const data = JSON.stringify({ message: 'New update at ' + new Date().toLocaleTimeString() });
    // SSE messages must start with "data: " and end with two newlines
    res.write(`data: ${data}\n\n`);
  }, 3000);

  // Stop sending data if the user closes the page
  req.on('close', () => clearInterval(interval));
}).listen(3000);

console.log('Server running on http://localhost:3000');

What you should see: When you run node server.js and visit the URL in your browser, you won't see a normal webpage. Instead, you will see a new line of text appearing every three seconds as the server "pushes" updates to you.

Step 2: How do you receive data in the browser?

The browser provides a built-in tool called EventSource (a JavaScript interface used to receive server-sent events) specifically for this purpose. You don't need to install any external libraries or packages to make this work.

Create an index.html file and add this script:

// Connect to our server route
const eventSource = new EventSource('http://localhost:3000');

// Listen for new messages coming from the server
eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Update received:', data.message);
  
  // Update the UI with the new data
  const list = document.getElementById('updates');
  const item = document.createElement('li');
  item.textContent = data.message;
  list.appendChild(item);
};

// Handle potential errors
eventSource.onerror = () => {
  console.error('The connection was lost.');
  eventSource.close();
};

What you should see: When you open this HTML file, your browser will automatically connect to the server. Every three seconds, a new bullet point will appear on your screen without you ever refreshing the page.

How does SSE work with modern AI models?

One of the most common uses for SSE in 2026 is streaming responses from Large Language Models (LLMs). When you use GPT-5 or Claude Sonnet 4, the model generates text one token (a small unit of text, like a word or part of a word) at a time.

If you waited for the entire response to finish, the user might be staring at a blank screen for 10 or 20 seconds. By using SSE, you can stream each word to the UI as soon as the AI generates it.

We found that using SSE for AI streaming reduces the "perceived latency" (how fast a system feels to a user) significantly. Even if the total generation time is the same, the user stays engaged because they see progress immediately.

What are the common mistakes to avoid?

It is normal to run into a few hurdles when first setting up real-time streams. Most issues relate to how the connection is managed between the server and the client.

  • Forgetting the double newline: SSE messages must end with \n\n. If you only include one, the browser will keep waiting for more data and will never trigger the onmessage event.
  • Buffering issues: Some proxy servers or security tools try to "buffer" (hold onto data until a certain amount is reached) before sending it to the user. This breaks the real-time effect.
  • Connection limits: While HTTP/3 has largely solved this, older environments might limit you to six streams. Always remember to close your connection using eventSource.close() when it is no longer needed.

Don't worry if your first attempt results in a "connection lost" error. This usually means the server script crashed or the URL in your EventSource doesn't match your server's address.

Next Steps

Now that you understand the basics of Server-Sent Events, you can start integrating them into more complex projects. You might try building a live price tracker for digital assets or a simple chat notification system.

To expand your skills, look into "Named Events," which allow you to send different types of data over the same stream by using the event: field in your server response. This lets your browser distinguish between a "chat" message and a "system" alert.

For a deeper dive into the technical specifications and advanced configurations, check out the official MDN documentation for Server-Sent Events.


Read the Server Documentation