Server-sent events (SSE) provide an easy way of transferring real-time updates from the server to the client. Unlike WebSockets, which allow two-way communication, SSE stresses a one-directional stream from server to client, perfect for usage in real-time notifications, stock price updates, or tracking progress.
The SSE implementation strategies of Express.js will be covered in this post. I have also created a GitHub repository including a working example to streamline issues.


Why using SSE?

SSE has numerous benefits.

Simplicity: Implementing less complex than WebSockets.
Built-in Support: Designed from the box with modern web browsers utilizing the `EventSource`, API.
lightweight: perfect for usage in situations when two-way interaction is not necessary.
Automatic Reconnection: Should a connection break off, the browser manages automatic reconnection.


Creating SSE with Express.js

Let's explore developing a basic Express.js SSE server.

First step: install dependencies

Check you have Node.js installed first. Initiate a fresh project, then install Express:

npm init -y
npm install express

Second Step: Create the Server

Here's how to create an Express server sending SSE updates:

const express = require('express');
const app = express();
const PORT = 3000;

// SSE route
app.get('/events', (req, res) => {
    // Set headers to enable SSE
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    // Send an initial event
    res.write('data: Connected to SSE\n\n');

    //send events
    const interval = setInterval(() => {
    // you can get data from API also
        const message = { timestamp: new Date().toISOString(), data: "Hello from SSE!" };
        res.write(`data: ${JSON.stringify(message)}\n\n`);
    }, 3000);

    // Clean up on client disconnect
    req.on('close', () => {
        clearInterval(interval);
        console.log('Client disconnected');
    });
});

// Start the server
app.listen(PORT, () => {
    console.log(`SSE server running at http://localhost:${PORT}`);
});

Third Step: The Frontend

Frontend listens for SSE updates using EventSource API.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE with Express.js</title>
</head>
<body>
    <h1>Server-Sent Events Demo</h1>
    <div id="events"></div>
	
    <script>
    // using EventSource API
        const eventSource = new EventSource('/events');
        // lsiten to the event update
        eventSource.onmessage = (event) => {
            const data = JSON.parse(event.data);
            const eventDiv = document.createElement('div');
            eventDiv.textContent = `Received at ${data.timestamp}: ${data.data}`;
            document.getElementById('events').appendChild(eventDiv);
        };

        eventSource.onerror = () => {
            console.error('Error occurred');
        };
    </script>
</body>
</html>

Running the Example

  • Create a clone of the GitHub repository.

    git clone https://github.com/amdsaad/sse-express-js.git
  • Get to the project directory and install dependencies:

    cd sse-express-js
    npm install
  • Starting the server

    node server.js
  • Open the index.html file in your browser. Live updates streaming in should be seen here.

Use Cases for SSE

SSE is ideal for situations where the server must send updates to the client. like:

  • Live notifications, messages, or updates sent to the user.
  • Updating stock prices, weather data, or analytics is the real-time dashboard.
  • Monitoring long-standing projects task progress.

SSE's Limitations

SSE has certain limitations, even if it is really strong:

One-way: Designed just for server-to-client communication.

HTTP/2 Recommended for Scalability: Managing several connections effectively needs a HTTP/2.

SSE solely supports text data; there is no binary data.

For two-way communication, give WebSockets some thought.


Frequently Asked Questions

  • What's the difference between SSE and WebSockets?
    For one-way communication, SSE is easier and better; WebSockets enable two-way communication.

     

  • Which browsers run SSE?
    SSE is supported by most modern web browsers, including Chrome, Edge, Firefox, and Safari.

     

  • Can I send SSE JSON data?
    Yes! Serialize your data using JSON.straggle before forwarding it.

To summarize up


Real-time changes can be easily implemented with server-sent events simply yet powerfully. Express.js lets you rapidly create an SSE server and link it with a client application using EventSource API.

Start exploring with SSE in your projects by consulting the GitHub repository for the whole code.