EventSource Client for Node.js and Browsers
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
-
error TS2304: Cannot find name 'Event'.
cause TypeScript compiler cannot locate the global 'Event' type definition.fixConfigure your `tsconfig.json` to include the appropriate `lib` entry (e.g., `"lib": ["dom"]` for browsers) or ensure `@types/node` (>=18) is installed for Node.js environments. -
error TS2304: Cannot find name 'EventTarget'.
cause TypeScript compiler cannot locate the global 'EventTarget' type definition.fixConfigure your `tsconfig.json` to include the appropriate `lib` entry (e.g., `"lib": ["dom"]` for browsers) or ensure `@types/node` (>=18) is installed for Node.js environments. -
error TS2304: Cannot find name 'MessageEvent'.
cause TypeScript compiler cannot locate the global 'MessageEvent' type definition.fixConfigure your `tsconfig.json` to include the appropriate `lib` entry (e.g., `"lib": ["dom"]` for browsers) or ensure `@types/node` (>=18) is installed for Node.js environments. -
TypeError: EventSource is not a constructor (or similar CJS module error)
cause Attempting to use `EventSource` as a default export or via `require()` in environments where it expects a named ESM export.fixFor versions `>=3.0.0`, use `import { EventSource } from 'eventsource';`. If you must use CommonJS, consider transpiling or using an older major version (2.x) that supported CommonJS default exports directly.
Warnings
- breaking Node.js v18 support has been dropped. The package now requires Node.js v20 or higher.
- breaking The `FetchLikeInit` TypeScript type has been removed and replaced with `EventSourceFetchInit`.
- breaking The `EventSource` module now uses a named export instead of a default export. Also, UMD bundles are no longer provided, requiring a bundler for browser environments.
- breaking Direct `headers`, HTTP/HTTPS proxy support, and `https.*` options within the `EventSource` constructor's init dictionary have been removed.
- gotcha TypeScript compilation errors ('Cannot find name 'Event'', 'EventTarget'', 'MessageEvent'') occur when `tsconfig.json` is not correctly configured for the target environment.
Install
-
npm install eventsource -
yarn add eventsource -
pnpm add eventsource
Imports
- EventSource
import EventSource from 'eventsource'
import { EventSource } from 'eventsource' - EventSourceFetchInit
import type { EventSourceFetchInit } from 'eventsource'
Quickstart
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);