In this example, I will give you a detailed explanation of how the Server-Sent Events (SSE) work using ExpressJS.
- First, we install the required dependencies:
npm install express express-sse
express is used to create the web server, and express-sse is a middleware for facilitating the implementation of server-sent events.
- Then, we create an
app.js file and import the necessary modules and create instances:
const express = require('express');
const SSE = require('express-sse');
const app = express();
const sse = new SSE();
app is the instance of the Express server, and sse is the instance of the express-sse middleware. The express-sse library simplifies handling of server-sent events in Express.
- Next, we define the routes.
The first route serves the index.html file containing the client-side code:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
The second route /events is for clients to subscribe to server-sent events. When clients connect to this route, they will receive a stream of server-sent events:
app.get('/events', sse.init);
sse.init is a middleware that handles the incoming request and sets up the SSE connection for the client.
The third route /update is an endpoint for simulating data updates. When the server receives a POST request at this endpoint, it pushes the updated data to all connected clients:
app.post('/update', (req, res) => {
let data = {
timestamp: new Date().toISOString(),
message: 'Data updated',
};
// Send updated data to clients
sse.send(data);
res.status(204).end();
});
sse.send(data) sends the data as a server-sent event message to all connected clients.
- Now, we start the Express server:
const port = 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
- We also create an
index.html file containing the client-side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Server-Sent Events Example</title>
<script>
// Connect to the Server-Sent Events route
const source = new EventSource('/events');
// Listen for 'message' events and update the page
source.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
const content = document.createElement('li');
content.textContent = `${data.timestamp}: ${data.message}`;
document.querySelector('#list').append(content);
});
</script>
</head>
<body>
<h1>Server-Sent Events Example</h1>
<ul id="list"></ul>
</body>
</html>
In this HTML file, we create an EventSource object to connect to the /events route. This connection allows the client to receive server-sent events from the server:
const source = new EventSource('/events');
Next, we add an event listener for the 'message' event. When the client receives a message event, it parses the event data (JSON), creates a new <li> element, and appends the new element to the DOM:
source.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
const content = document.createElement('li');
content.textContent = `${data.timestamp}: ${data.message}`;
document.querySelector('#list').append(content);
});
- Finally, start the server:
node app.js
Now, when you open the browser and navigate to http://localhost:3000, you will see the client-side code receiving server-sent events. If you send a POST request to /update, you'll see the updates showing up on the client in real-time.