Registry / http-networking / eventsource-client

eventsource-client

JSON →
library1.2.0jsnpmunverified

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.

npm install eventsource-client
INSTALL
IMPORT
SIG · EVENTSOURCE-CLIENT
E
eventsource-client
http-networkingjavascriptv1.2.0
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createEventSource
✓ import { createEventSource } from 'eventsource-client'
✗ const { createEventSource } = require('eventsource-client')
Primary entry point for creating an EventSource connection. While CJS is supported, ESM is the recommended modern approach.
EventSourceClientOptions
✓ import type { EventSourceClientOptions } from 'eventsource-client'
✗ import { EventSourceClientOptions } from 'eventsource-client'
Import as a type for compile-time checking. Do not import as a value.
EventSourceMessage
✓ import type { EventSourceMessage } from 'eventsource-client'
✗ import { EventSourceMessage } from 'eventsource-client'
Import as a type for compile-time checking. Do not import as a value.

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);
Debug
Known issues
breakingVersion 1.0.0 introduced a breaking change requiring Node.js 18 or higher due to its reliance on modern Web Streams and Fetch API, which are native in Node.js >= 18.
fix
Upgrade your Node.js environment to version 18 or newer, or ensure you are using a compatible runtime like modern browsers, Deno, or Bun. If using an older Node.js, you might need to polyfill `fetch` and `ReadableStream`.
affects: >=1.0.0
gotchaThis library does NOT aim to be API-compatible with the browser's native `EventSource` API. It offers a different, more flexible interface with additional features (e.g., custom headers, POST requests, async iterators). Users expecting a drop-in replacement may find the API surface unfamiliar.
fix
Review the documentation for `createEventSource` options and its return object (especially the async iterator pattern) to understand its distinct API.
affects: >=1.0.0
gotchaWhen using the async iterator pattern (`for await...of`), the EventSource connection is NOT automatically closed when the loop breaks or completes. You must explicitly call `es.close()` to terminate the connection and prevent resource leaks or unwanted reconnections.
fix
Always include `es.close()` after your `for await...of` loop, or within error handling, to ensure the connection is properly terminated.
affects: >=1.0.0
gotchaIn environments where `fetch` is not globally available (e.g., older Node.js versions or specific restricted browser contexts), you must provide a `fetch` implementation in the `createEventSource` options.
fix
Pass your chosen `fetch` polyfill or implementation as the `fetch` option: `createEventSource({ url: '...', fetch: yourFetchImpl })`.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: fetch is not a function
The runtime environment (e.g., Node.js < 18 or a browser without native Fetch API) does not have a global `fetch` implementation, and one was not provided.
fix
Upgrade your Node.js environment to v18+ or provide a `fetch` implementation (e.g., `node-fetch`) via the `fetch` option in `createEventSource`.
TypeError: createEventSource is not a function
Incorrect import statement (e.g., using `require()` for a package primarily designed for ESM, or wrong named import syntax in CJS context).
fix
Ensure you are using `import { createEventSource } from 'eventsource-client'` for ESM or `const { createEventSource } = require('eventsource-client')` for CommonJS, and that your build setup correctly handles module resolution.
TypeError: (intermediate value) is not async iterable
Attempting to use `for await...of` on the `createEventSource` return value in an environment that does not support `Symbol.asyncIterator` or where the stream is not correctly initialized as an async iterable.
fix
Ensure your environment supports `Symbol.asyncIterator` (Node.js >= 18, modern browsers). If issues persist, consider using the callback-based `onMessage` API instead of the async iterator.
Upgrade
Version history
1.2.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
21 hits · last 30 days
node
18
OpenAI (training)
1
Resources
eventsource-client — npm install eventsource-client · libregistry