Modern EventSource Client

1.2.0 · active · verified Tue Apr 21

eventsource-client is a modern, streaming client for Server-Sent Events (SSE) that operates across both Node.js and browser environments. The package is currently at version 1.2.0 and maintains an active release cadence, with multiple minor updates and bug fixes released throughout the year. It distinguishes itself from traditional EventSource polyfills by not aiming for API compatibility with the browser's native EventSource API. Instead, it offers a more flexible and robust approach, leveraging modern web APIs like `fetch()` and Web Streams. Key differentiators include support for async iterator patterns, various HTTP request methods (POST, PATCH, DELETE), custom headers, request bodies, configurable reconnection policies, and the ability to subscribe to any event name, including the `error` event, along with setting an initial `Last-Event-ID`. The library ships with both ESM and CommonJS versions for broad compatibility.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to an SSE endpoint using `createEventSource` with callback handlers for messages, connection status, and errors. Also highlights explicit connection closing.

import { createEventSource } from 'eventsource-client';

async function connectToSSE() {
  const sseUrl = 'https://my-server.com/sse'; // Replace with your SSE endpoint

  const es = createEventSource({
    url: sseUrl,
    // Optional: provide a custom fetch implementation if needed, e.g., for Node.js < 18 or specific proxying.
    // fetch: customFetchFunction,
    onMessage: ({ data, event, id }) => {
      console.log(`Received Event - ID: ${id ?? 'N/A'}, Event: ${event ?? 'message'}, Data: ${data}`);
    },
    onOpen: () => {
      console.log('SSE connection opened.');
    },
    onDisconnect: () => {
      console.log('SSE connection disconnected.');
    },
    onError: (err) => {
      console.error('SSE Error:', err);
    }
  });

  // You can also use the async iterator pattern:
  // for await (const { data } of es) {
  //   console.log('Data (from iterator): %s', data);
  //   // You might want to break out of this loop based on some condition
  //   // and call es.close() manually.
  // }

  console.log('Current readyState:', es.readyState);
  console.log('Last Event ID:', es.lastEventId);

  // To prevent indefinite connection or reconnects, call close() when done.
  // For demonstration, let's close after 10 seconds if still open.
  setTimeout(() => {
    if (es.readyState !== 'closed') {
      console.log('Closing SSE connection after timeout.');
      es.close();
    }
  }, 10000);
}

connectToSSE().catch(console.error);

view raw JSON →