mpetrunic / fastify-sse-v2

Provide Server-Sent Events to Fastify
MIT License
99 stars 19 forks source link
fastify fastify-plugin server-sent-events sse typescript

Fastify SSE Plugin

CI check npm version

Fastify plugin for sending Server-sent events.

For fastify@2.x use fastify-sse-v2@1.x!

How to use?

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);

Sending events from AsyncIterable source

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" };
      }
    })()
  );
});

Sending individual events

import { FastifySSEPlugin } from "fastify-sse-v2";

const server = fastify();
server.register(FastifySSEPlugin);

server.get("/", async function (req, res) {
  for (let i = 0; i < 10; i++) {
    await sleep(2000);
    res.sse({ id: String(i), data: "Some message" });
  }
});

fastify.get("/listenForChanges", {}, (request, reply) => {
  const listenStream = fastify.db
    .watch("doc-uuid")
    .on("data", (data) => reply.sse({ data: JSON.stringify(data) }))
    .on("delete", () => reply.sse({ event: "close" }));
  request.socket.on("close", () => listenStream.end());
});
Note
Sending events from EventEmmiters
import { FastifySSEPlugin } from "fastify-sse-v2";
import { on } from "events";

const server = fastify();
server.register(FastifySSEPlugin);

server.get("/", function (req, res) {
  res.sse(
    (async function* () {
      for await (const [event] of on(eventEmmitter, "update")) {
        yield {
          event: event.name,
          data: JSON.stringify(event),
        };
      }
    })()
  );
});
Note
Change server send retry behavior
import { FastifySSEPlugin } from "fastify-sse-v2";

const server = fastify();

server.register(FastifySSEPlugin) // retryDelay default 3000

server.register(FastifySSEPlugin, {
  retryDelay: false // disable retryDelay
  retryDelay: 5000 // override 5000
})
Note