Fastify Server-Sent Events (SSE) Plugin

4.2.2 · active · verified Sun Apr 19

fastify-sse-v2 is a Fastify plugin designed to streamline the implementation of Server-Sent Events (SSE) within a Fastify application. It augments the `FastifyReply` object with a `.sse()` method, enabling developers to send individual events or stream events from `AsyncIterable` or `EventEmitter` sources, thereby abstracting the underlying HTTP streaming complexities. The current stable version is 4.2.2, with releases occurring periodically, typically every few months, to address bug fixes and introduce minor features. A primary differentiator is its seamless integration with Fastify's reply object and robust support for modern async/await patterns in event streaming. It also provides configurable options for `retryDelay` to manage client reconnection logic and `highWaterMark` to control internal stream buffering, offering fine-grained control over SSE behavior.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a Fastify server with fastify-sse-v2 to stream events using an AsyncIterable source, sending five messages at 1.5-second intervals.

import Fastify from 'fastify';
import { FastifySSEPlugin } from 'fastify-sse-v2';

const fastify = Fastify({ logger: true });

fastify.register(FastifySSEPlugin);

// Helper to simulate async work
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

fastify.get('/events', function (request, reply) {
  reply.sse(
    (async function* source() {
      for (let i = 0; i < 5; i++) {
        await sleep(1500);
        const eventData = { id: String(i), data: `Message ${i} at ${new Date().toISOString()}` };
        fastify.log.info(`Sending event: ${JSON.stringify(eventData)}`);
        yield eventData;
      }
      fastify.log.info('SSE stream finished.');
    })()
  );
});

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

view raw JSON →