It's a Express middleware that simply and easily using Server Sent Events (SSE)
npm install express-sse-middleware
import express from 'express';
import { sseMiddleware } from 'express-sse-middleware';
app.use(sseMiddleware);
app.get('/path', (req, res) => {
const sse = res.sse(); // `adding Response.sse()` funciton
let count = 0;
setInterval(() => {
sse.send(String(count++));
}, 1000);
// sent incremented number every second.
// ↓
// data: 0
// data: 1
// data: ...
});
app.listen(3000);
Prepared a simple event builder.
but params of send
function is so simple that No need to use.
let count = 0;
const builder = new EventBuilder() // <- Builder instance is immutable.
.id('test_id')
.event('event_name');
setInterval(() => {
sse.send(builder.data(String(count++)).build());
}, 1000);
// ↓
// id: test_id
// event: event_name
// data: 0
//
// id: test_id
// event: event_name
// data: 1
This middleware is not depend on anything.