Better SSE

0.16.1 · active · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { createSession } from 'better-sse';
import express from 'express';

const app = express();
const port = 3000;

app.get('/events', (req, res) => {
  // Ensure client doesn't cache the response
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Connection', 'keep-alive');

  const session = createSession(req, res);

  // Optionally, send an initial event
  session.push('Hello from the server!', 'greeting');

  // Periodically send data
  let counter = 0;
  const interval = setInterval(() => {
    if (session.isClosed()) {
      clearInterval(interval);
      console.log('Session closed, stopping updates.');
      return;
    }
    session.push(`Data update ${counter++}`, 'update');
  }, 2000);

  // Handle client disconnect
  session.on('close', () => {
    clearInterval(interval);
    console.log('Client disconnected.');
  });
});

app.listen(port, () => {
  console.log(`SSE server listening at http://localhost:${port}`);
  console.log('Connect with a browser using EventSource: new EventSource("http://localhost:3000/events")');
});

view raw JSON →