In Node.js, we can implement Server-Sent Events easily using the standard http
module along with the EventEmitter
module.
Server-Sent Events (SSE, events sent from the server) are a technology that allows us to send real-time updates from the server to the client, through unidirectional communication.
The advantages of Server-Sent Events are:
- Simplicity: SSEs are easy to implement on both the server and client without the need for external libraries
- Compatibility: They are compatible with most modern browsers without the need for additional libraries or polyfills
- Automatic Reconnection: In case of disconnection, the browser will automatically attempt to reconnect to the server, ensuring more stable communication
Unlike Websockets, which provide bidirectional communication, SSEs are ideal for scenarios where we only need to send updates from the server to the client
Example of Server-Sent Events in Node.js
Let’s see a basic example of how to create an SSE server and how to handle connection and message events.
Creating the SSE Server
First, we create an SSE server in Node.js that handles client communications.
import http from 'http';
// Function to send events to the client
function sendEvent(res, event, data) {
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
// Create HTTP server
const server = http.createServer((req, res) => {
// Header to indicate that SSE events are being sent
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// Send an event every 5 seconds
const interval = setInterval(() => {
sendEvent(res, 'message', { message: 'Hello from the server' });
}, 5000);
// Handle client connection close
req.on('close', () => {
clearInterval(interval);
console.log('Client disconnected');
});
});
const port = 3030;
server.listen(port, () => {
console.log(`SSE server started on http://localhost:${port}`);
});
In this example:
- An HTTP server is created that listens on port 3000.
- When a client connects, the server sets the
Content-Type
header totext/event-stream
to indicate that SSE events will be sent. - Every 5 seconds, an event is sent to the client with a JSON message.
- When a client disconnects, the event sending interval is cleared.
SSE Web Client (Frontend)
On the client side, we can use JavaScript to receive and handle events sent by the server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SSE Client</title>
</head>
<body>
<div id="message"></div>
<script>
const messageDiv = document.getElementById('message');
const evtSource = new EventSource('http://localhost:3030');
evtSource.onmessage = function(event) {
const data = JSON.parse(event.data);
messageDiv.innerHTML = 'Message from server: ' + data.message;
};
evtSource.onerror = function(event) {
console.error('SSE Error:', event);
evtSource.close();
};
</script>
</body>
</html>
In this HTML client example, we create an EventSource
pointing to our SSE server at http://localhost:3030
. When the client receives an event (onmessage
), we update the content of an HTML element with the current time sent from the server.
To test it:
- Run the Node.js server that sends SSE events.
- In a browser, navigate to the address
localhost:3030
- You should see the server message updating every 5 seconds on the page
Download the Code
All the code from this post is available for download on Github