Middleware to facilitate server-sent events.
Options
Option |
Type |
Default |
Description |
autoInit |
Boolean |
false |
Whether or not to automatically initialize (setup keepAlive, send headers, …) the SSE instance. |
keepAlive |
Number | [false] |
15000 |
Send keep-alive messages in the form of “: ping ” comments every keepAlive ms. Set false to disable. |
serialize |
Function |
JSON.stringify |
A function that is used to serialize data sent over the event stream. |
onInstance(instance, req, res) |
Function |
A function that sets the SSE instance to req.context.sse if you’re using the context middleware or res.locals.sse otherwise. |
|
SSE instance
Property |
Type |
Description |
enabled |
Boolean |
Indicate whether or not SSE is enabled for the current request. If false the send* functions are no-ops. |
send(event, data) |
Function |
Sends an event and data over the stream. Either parameter can be omitted to send an event without data or data without event respectively. |
sendComment(message) |
Function |
Sends a comment over the stream. |
Simple example
const app = require('express')();
const createContextMiddleware = require('@ambassify/expressify/middleware/context');
const createSSEMiddleware = require('@ambassify/expressify/middleware/server-sent-events');
app.use(createContextMiddleware());
app.use(createSSEMiddleware());
app.get('/test', (req, res) => {
if (!res.sendServerEvent) {
res.send('Server-sent events not enabled');
return;
}
res.sendServerEvent('user', { id: 1 });
res.sendServerEvent('user', { id: 2 });
res.sendServerEvent(null, { some: 'data' });
res.sendServerEvent('ping');
req.context.sse.sendComment('Just a comment');
res.end();
});
Customized example
const app = require('express')();
const createSSEMiddleware = require('@ambassify/expressify/middleware/server-sent-events');
app.use(createSSEMiddleware({
serialize: data => data.toString(),
onInstance(instance, req, res) {
req.isEventStream = instance.enabled;
res.streamEvent = instance.send;
res.locals.initSSE = instance.init;
}
}));
app.get('/test', (req, res) => {
if (!req.isEventStream) {
res.send('Server-sent events not enabled');
return;
}
// Set some custom headers before init
res.header('x-custom-header', 'foo');
res.locals.initSSE();
res.streamEvent('user', { id: 1 }); // will send "data: [Object object]"
res.end();
});