{"id":15294,"library":"better-sse","title":"Better SSE","description":"Better SSE is a robust, dependency-less, and spec-compliant implementation of Server-Sent Events (SSE) written entirely in TypeScript. It provides a streamlined, framework-agnostic solution for pushing data from a server to clients over HTTP, making it an alternative to WebSockets for unidirectional data flows. Currently stable at version 0.16.1, the project demonstrates a consistent release cadence with updates addressing compatibility, new features like connection adapters and event batching, and continuous type improvements. Key differentiators include its full TypeScript support, extensive documentation, 100% test coverage, and compatibility across various Node.js frameworks and runtimes (e.g., Express, Hono, Fastify, Bun, Deno), operating directly over the HTTP protocol to reduce bandwidth and complexity compared to other real-time solutions.","status":"active","version":"0.16.1","language":"javascript","source_language":"en","source_url":"https://github.com/MatthewWid/better-sse","tags":["javascript","server-sent-events","sse","realtime","real-time","tcp","events","typescript"],"install":[{"cmd":"npm install better-sse","lang":"bash","label":"npm"},{"cmd":"yarn add better-sse","lang":"bash","label":"yarn"},{"cmd":"pnpm add better-sse","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"ESM is the primary import style; CommonJS `require` might have issues in older versions or specific environments, especially before v0.14.0.","wrong":"const { createSession } = require('better-sse')","symbol":"createSession","correct":"import { createSession } from 'better-sse'"},{"note":"`createChannel` is a named export. Attempting a default import will result in `undefined`.","wrong":"import createChannel from 'better-sse'","symbol":"createChannel","correct":"import { createChannel } from 'better-sse'"},{"note":"`Session` is a TypeScript type, not a runtime value. Import it using `import type` to avoid bundling issues or runtime errors.","wrong":"import { Session } from 'better-sse'","symbol":"Session","correct":"import type { Session } from 'better-sse'"}],"quickstart":{"code":"import { createSession } from 'better-sse';\nimport express from 'express';\n\nconst app = express();\nconst port = 3000;\n\napp.get('/events', (req, res) => {\n  // Ensure client doesn't cache the response\n  res.setHeader('Cache-Control', 'no-cache');\n  res.setHeader('Content-Type', 'text/event-stream');\n  res.setHeader('Connection', 'keep-alive');\n\n  const session = createSession(req, res);\n\n  // Optionally, send an initial event\n  session.push('Hello from the server!', 'greeting');\n\n  // Periodically send data\n  let counter = 0;\n  const interval = setInterval(() => {\n    if (session.isClosed()) {\n      clearInterval(interval);\n      console.log('Session closed, stopping updates.');\n      return;\n    }\n    session.push(`Data update ${counter++}`, 'update');\n  }, 2000);\n\n  // Handle client disconnect\n  session.on('close', () => {\n    clearInterval(interval);\n    console.log('Client disconnected.');\n  });\n});\n\napp.listen(port, () => {\n  console.log(`SSE server listening at http://localhost:${port}`);\n  console.log('Connect with a browser using EventSource: new EventSource(\"http://localhost:3000/events\")');\n});","lang":"typescript","description":"This quickstart demonstrates setting up a basic Server-Sent Events endpoint using Express. It initializes a session for a new client connection, sends an initial greeting, and then periodically pushes updates until the client disconnects."},"warnings":[{"fix":"Review the documentation on 'Connection Adapters' if encountering issues with specific frameworks or runtimes. Update to v0.16.1 for fixes related to Node HTTP/1 and HTTP/2 compatibility issues in emulated environments.","message":"Introduction of 'Connection Adapters' in v0.16.0 changed how connections are managed. While not strictly API breaking for simple use cases, custom or complex integrations might need to adapt to this new abstraction, especially when running on environments that do not fully emulate Node's HTTP APIs.","severity":"breaking","affected_versions":">=0.16.0"},{"fix":"Upgrade to better-sse v0.14.0 or newer to ensure correct ESM import behavior. For older versions, carefully check module resolution configurations (e.g., `\"type\": \"module\"` in `package.json`, `tsconfig.json` settings).","message":"Prior to v0.14.0, there were minor issues when importing the package into an ES Module (ESM) environment. Consumers might have encountered unexpected behavior or errors related to module resolution.","severity":"gotcha","affected_versions":"<0.14.0"},{"fix":"Upgrade to v0.16.1 or newer, which includes a fix for this crash by gracefully handling the absence of `setNoDelay`.","message":"When using frameworks that do not fully implement Node's HTTP/1 or HTTP/2 Compatibility APIs (e.g., some edge runtimes or newer frameworks), v0.16.0 could crash due to missing `setNoDelay` methods.","severity":"gotcha","affected_versions":"0.16.0"},{"fix":"Update to v0.12.1 or later to benefit from enhanced TypeScript type inference and suggestions for event names, improving developer experience and reducing errors.","message":"Event name suggestions for `Session` and `Channel` event listeners were improved in v0.12.1. Older versions might lack proper TypeScript autocompletion for event names, leading to potential typos or runtime errors.","severity":"gotcha","affected_versions":"<0.12.1"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure you are using ES module imports: `import { createSession } from 'better-sse';`. If in a CommonJS context, consider configuring your project to support ESM or using an older version if available (though newer versions are ESM-first).","cause":"Attempting to use `require` for a package primarily designed for ES modules, or incorrect named import.","error":"TypeError: createSession is not a function"},{"fix":"Ensure `res.setHeader()` calls for `Cache-Control`, `Content-Type`, and `Connection` are made *before* `createSession(req, res)` or any data is written to the response stream. This often means placing them early in your SSE route handler.","cause":"Attempting to modify response headers after SSE session has started or other middleware has sent initial headers.","error":"Headers already sent. Cannot set headers after they are sent to the client."},{"fix":"Implement proper session cleanup by listening to the `close` event on the `Session` object (`session.on('close', () => { /* cleanup resources */ });`) to stop sending events or clear timers specific to that client.","cause":"Client disconnected abruptly, leading to a connection reset by the peer on the server side.","error":"Error: read ECONNRESET"}],"ecosystem":"npm"}