Fastify plugin for sending Server-sent events.
For fastify@2.x
use fastify-sse-v2@1.x!
yarn add fastify-sse-v2
Register fastify-sse-v2 plugin into your fastify instance:
import {FastifySSEPlugin} from "fastify-sse-v2";
const server = fastify();
server.register(FastifySSEPlugin);
import {FastifySSEPlugin} from "fastify-sse-v2";
const server = fastify();
server.register(FastifySSEPlugin);
server.get("/", function (req, res) {
res.sse((async function * source () {
for (let i = 0; i < 10; i++) {
sleep(2000);
yield {id: String(i), data: "Some message"};
}
})());
});
import {FastifySSEPlugin} from "fastify-sse-v2";
import EventIterator from "event-iterator";
const server = fastify();
server.register(FastifySSEPlugin);
server.get("/", function (req, res) {
const eventEmitter = new EventEmitter();
res.sse(new EventIterator(
(push) => {
eventEmitter.on("some_event", push)
return () => eventEmitter.removeEventListener("some_event", push)
}
)
);
});
- to remove event listeners (or some other cleanup) when client closes connection, you can listen on fastify's req.raw connection close event: