Skip to content

Understanding Server-Sent Events (SSE)

Server-Sent Events, a standard for unidirectional communication between a server and a web client over HTTP.

It allows servers to push updates to clients in real-time, making it ideal for applications like live notifications, real-time feeds, and updates.

Key Points of SSE

Common Use Cases

Example

In this example, the server sends a JSON object with the current time every second. The client listens for messages and logs the received data to the console.

Server (Node.js)

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

    // Send data periodically
    const intervalId = setInterval(() => {
        res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);
    }, 1000);

    // Clean up on client disconnect
    req.on('close', () => {
        clearInterval(intervalId);
    });
});

Client (JavaScript)

const eventSource = new EventSource('/events');

eventSource.onmessage = (event) => {
    console.log('Received data:', event.data);
};

Comparison with WebSockets

FeatureSSEWebSockets
CommunicationOne-way (server -> client)Two-way (full-duplex)
ProtocolHTTPCustom TCP protocol
ComplexitySimpleMore complex
ReconnectionBuilt-inNeeds to be implemented
Binary Data SupportNoYes

Summary

Server-Sent Events provide a simple and efficient way to push real-time updates from the server to the client. It is a lightweight alternative to WebSockets for applications that require unidirectional communication.

By using SSE, you can create real-time features like live notifications, feeds, and updates without the complexity of bidirectional communication.

References