Welcome to Express-SSE: The Simplest Way to Implement Server-Sent Events (SSE)
Server-Sent Events (SSE) is a technology that enables a server to push real-time updates to the client over a single HTTP connection. The express-sse
package is a simple tool that makes implementing SSE in Node.js applications easier, especially within an Express framework. In this article, we will introduce you to express-sse and explore its useful APIs through various code snippets.
Installation
npm install express --save
npm install express-sse --save
Basic Setup
Setting up express-sse is straightforward. Here’s a simple example:
const express = require('express');
const SSE = require('express-sse');
const app = express();
const sse = new SSE();
app.get('/stream', (req, res) => {
sse.init(req, res);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Sending Messages
Sending messages to the client using express-sse is simple. Here’s how you can do it:
sse.send('hello world');
Broadcasting Events
If you want to broadcast events to all connected clients, you can use the send
method:
sse.send('new message', 'messageType');
Data with Custom ID and Retry
You can also specify a custom ID and retry interval for the event:
sse.send('data', 'eventType', { id: 'custom-id', retry: 5000 });
Clients Tracking
Tracking clients currently connected to the SSE endpoint can be done as shown below:
console.log(sse.clients);
Complete App Example
Below is a more complete example of an express application utilizing express-sse:
const express = require('express');
const SSE = require('express-sse');
const app = express();
const sse = new SSE(['initial message']);
app.get('/stream', (req, res) => {
sse.init(req, res);
});
app.get('/send', (req, res) => {
sse.send('new data received');
res.send('Data Sent');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Test the Application
Start the server and open http://localhost:3000/stream
in your browser. Then, visit http://localhost:3000/send
to see messages being pushed to the stream endpoint.
Happy coding!
Hash: bb59447354962aee5f168b2a3ce2575fc0c5f120d5bc0fa1b22499679ae09b56