EventSource Client for Node.js and Browsers

4.1.0 · active · verified Tue Apr 21

This package provides a WhatWG/W3C compliant EventSource client, enabling applications to consume Server-Sent Events (SSE) in both Node.js and modern browser environments. The current stable version is 4.1.0, with regular updates and major releases approximately every six months, indicating active maintenance. It aims for a minimal implementation closely adhering to the specification, distinguishing itself from alternatives like `eventsource-client` which offer a more flexible API. It supports Node.js versions 20 and higher, along with a wide range of modern browsers, Deno, and Bun, by leveraging standard web APIs like `fetch`, `ReadableStream`, and `TextDecoder`. The library also provides a mechanism to override the `fetch` implementation, offering greater control in diverse runtime environments. TypeScript types are shipped directly with the package, requiring appropriate `tsconfig.json` setup for correct type inference depending on the target environment.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to an SSE endpoint, listening for various event types, handling errors, and explicitly closing the connection.

import { EventSource } from 'eventsource';

// Replace with your SSE endpoint
const sseEndpoint = 'https://my-server.com/sse';

const es = new EventSource(sseEndpoint);

es.addEventListener('notice', (event) => {
  console.log('Notice received:', event.data);
});

es.addEventListener('update', (event) => {
  console.log('Update received:', event.data);
});

es.addEventListener('message', (event) => {
  console.log('Message received:', event.data);
});

es.addEventListener('error', (err) => {
  console.error('EventSource error:', err);
  if (err.code === 401 || err.code === 403) {
    console.log('Authentication or authorization failed.');
  }
});

console.log(`Connecting to SSE endpoint: ${sseEndpoint}`);

// Close the connection after 10 seconds to demonstrate clean shutdown
setTimeout(() => {
  console.log('Closing EventSource connection.');
  es.close();
}, 10_000);

view raw JSON →