{"id":10876,"library":"fastify-sse-v2","title":"Fastify Server-Sent Events (SSE) Plugin","description":"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.","status":"active","version":"4.2.2","language":"javascript","source_language":"en","source_url":"https://github.com/nodefactoryio/fastify-sse-v2","tags":["javascript","typescript"],"install":[{"cmd":"npm install fastify-sse-v2","lang":"bash","label":"npm"},{"cmd":"yarn add fastify-sse-v2","lang":"bash","label":"yarn"},{"cmd":"pnpm add fastify-sse-v2","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency, required for the plugin to function within a Fastify application.","package":"fastify","optional":false}],"imports":[{"note":"This is the main named export for registering the plugin. The package primarily uses ESM.","wrong":"const FastifySSEPlugin = require('fastify-sse-v2');","symbol":"FastifySSEPlugin","correct":"import { FastifySSEPlugin } from 'fastify-sse-v2';"},{"note":"The `sse` method is added to the `FastifyReply` instance by the plugin and is not directly imported. It's accessible after plugin registration.","symbol":"sse","correct":"reply.sse({ data: 'hello' });"},{"note":"While types are shipped, extending Fastify's interfaces is a common pattern to ensure TypeScript correctly recognizes the added `sse` method and `sseContext` property on `FastifyReply`.","symbol":"FastifyReply and SSE types","correct":"import { FastifyInstance, FastifyReply } from 'fastify';\ndeclare module 'fastify' {\n  interface FastifyReply {\n    sse: (payload: { id?: string; event?: string; data: string; retry?: number; comment?: string } | AsyncIterable<{ id?: string; event?: string; data: string; retry?: number; comment?: string }>) => void;\n    sseContext: { source: { end: () => void } };\n  }\n}"}],"quickstart":{"code":"import Fastify from 'fastify';\nimport { FastifySSEPlugin } from 'fastify-sse-v2';\n\nconst fastify = Fastify({ logger: true });\n\nfastify.register(FastifySSEPlugin);\n\n// Helper to simulate async work\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nfastify.get('/events', function (request, reply) {\n  reply.sse(\n    (async function* source() {\n      for (let i = 0; i < 5; i++) {\n        await sleep(1500);\n        const eventData = { id: String(i), data: `Message ${i} at ${new Date().toISOString()}` };\n        fastify.log.info(`Sending event: ${JSON.stringify(eventData)}`);\n        yield eventData;\n      }\n      fastify.log.info('SSE stream finished.');\n    })()\n  );\n});\n\nconst start = async () => {\n  try {\n    await fastify.listen({ port: 3000 });\n  } catch (err) {\n    fastify.log.error(err);\n    process.exit(1);\n  }\n};\n\nstart();","lang":"typescript","description":"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."},"warnings":[{"fix":"Migrate any logic dependent on the SSE stream's 'end' event to use `request.socket.on('close')` for client disconnection detection.","message":"The 'end' event, previously emitted when an SSE stream was closing, has been removed. Dependents on this event for cleanup or notification will need to find alternative mechanisms, such as listening to `request.socket.on('close')`.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Upgrade your Fastify application to version 4 or higher. Alternatively, for Fastify v3, use `fastify-sse-v2@1.x`.","message":"Version 3.0.0 dropped support for Fastify v3. This plugin now exclusively requires Fastify v4 or newer. Attempting to use it with Fastify v3 will result in compatibility issues.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Ensure `reply.sseContext.source.end()` is called to properly close the SSE stream when sending individual events, especially if the stream is meant to have a finite duration. For client disconnections, listen to `request.socket.on('close')`.","message":"When sending individual events using `reply.sse()`, the connection remains open indefinitely. It will only terminate if `reply.sseContext.source.end()` is explicitly called or the client disconnects.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Upgrade to `fastify-sse-v2@4.2.2` or newer to mitigate issues with exceptions occurring after headers have been sent.","message":"Exceptions thrown after headers have been sent in the SSE context can lead to unexpected behavior or unhandled errors. Version 4.2.2 introduced a fix for this scenario.","severity":"gotcha","affected_versions":"<4.2.2"},{"fix":"Upgrade to `fastify-sse-v2@4.2.1` or newer to ensure correct handling of newlines within event data payloads.","message":"Prior to version 4.2.1, newlines within event data were not handled properly, potentially corrupting the SSE stream format. This was addressed in `v4.2.1`.","severity":"gotcha","affected_versions":"<4.2.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you have called `fastify.register(FastifySSEPlugin);` before attempting to use `reply.sse()`. Also, verify that your Fastify version meets the peer dependency requirement (>=4.0.0 for plugin versions 3.x and above).","cause":"The `fastify-sse-v2` plugin was either not registered correctly, or your Fastify instance is too old for the plugin version used.","error":"Error: fastify.sse is not a function"},{"fix":"Implement checks to ensure the SSE stream is still active before attempting to send new events. For individual events, manage the lifecycle with `reply.sseContext.source.end()`. For `AsyncIterable` or `EventEmitter` sources, ensure your generator or event listener cleans up when the `request.socket.on('close')` event fires.","cause":"Attempting to write data to an SSE stream that has already been closed, either explicitly by calling `reply.sseContext.source.end()` or due to client disconnection.","error":"ERR_STREAM_WRITE_AFTER_END"},{"fix":"Once `reply.sse()` is called, the response is committed to an SSE stream. Do not attempt to modify headers or send a different type of response on the same request. Ensure all SSE-related logic is handled within the `reply.sse()` context.","cause":"You are attempting to send HTTP headers (e.g., calling `reply.send()` or similar methods) after the SSE connection has been initiated, which already sends specific headers for SSE.","error":"ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client"}],"ecosystem":"npm"}