{"id":15608,"library":"eventsource-client","title":"Modern EventSource Client","description":"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.","status":"active","version":"1.2.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/rexxars/eventsource-client","tags":["javascript","sse","eventsource","server-sent-events","typescript"],"install":[{"cmd":"npm install eventsource-client","lang":"bash","label":"npm"},{"cmd":"yarn add eventsource-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add eventsource-client","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary entry point for creating an EventSource connection. While CJS is supported, ESM is the recommended modern approach.","wrong":"const { createEventSource } = require('eventsource-client')","symbol":"createEventSource","correct":"import { createEventSource } from 'eventsource-client'"},{"note":"Import as a type for compile-time checking. Do not import as a value.","wrong":"import { EventSourceClientOptions } from 'eventsource-client'","symbol":"EventSourceClientOptions","correct":"import type { EventSourceClientOptions } from 'eventsource-client'"},{"note":"Import as a type for compile-time checking. Do not import as a value.","wrong":"import { EventSourceMessage } from 'eventsource-client'","symbol":"EventSourceMessage","correct":"import type { EventSourceMessage } from 'eventsource-client'"}],"quickstart":{"code":"import { createEventSource } from 'eventsource-client';\n\nasync function connectToSSE() {\n  const sseUrl = 'https://my-server.com/sse'; // Replace with your SSE endpoint\n\n  const es = createEventSource({\n    url: sseUrl,\n    // Optional: provide a custom fetch implementation if needed, e.g., for Node.js < 18 or specific proxying.\n    // fetch: customFetchFunction,\n    onMessage: ({ data, event, id }) => {\n      console.log(`Received Event - ID: ${id ?? 'N/A'}, Event: ${event ?? 'message'}, Data: ${data}`);\n    },\n    onOpen: () => {\n      console.log('SSE connection opened.');\n    },\n    onDisconnect: () => {\n      console.log('SSE connection disconnected.');\n    },\n    onError: (err) => {\n      console.error('SSE Error:', err);\n    }\n  });\n\n  // You can also use the async iterator pattern:\n  // for await (const { data } of es) {\n  //   console.log('Data (from iterator): %s', data);\n  //   // You might want to break out of this loop based on some condition\n  //   // and call es.close() manually.\n  // }\n\n  console.log('Current readyState:', es.readyState);\n  console.log('Last Event ID:', es.lastEventId);\n\n  // To prevent indefinite connection or reconnects, call close() when done.\n  // For demonstration, let's close after 10 seconds if still open.\n  setTimeout(() => {\n    if (es.readyState !== 'closed') {\n      console.log('Closing SSE connection after timeout.');\n      es.close();\n    }\n  }, 10000);\n}\n\nconnectToSSE().catch(console.error);","lang":"typescript","description":"Demonstrates connecting to an SSE endpoint using `createEventSource` with callback handlers for messages, connection status, and errors. Also highlights explicit connection closing."},"warnings":[{"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`.","message":"Version 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.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Review the documentation for `createEventSource` options and its return object (especially the async iterator pattern) to understand its distinct API.","message":"This 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always include `es.close()` after your `for await...of` loop, or within error handling, to ensure the connection is properly terminated.","message":"When 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Pass your chosen `fetch` polyfill or implementation as the `fetch` option: `createEventSource({ url: '...', fetch: yourFetchImpl })`.","message":"In 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Upgrade your Node.js environment to v18+ or provide a `fetch` implementation (e.g., `node-fetch`) via the `fetch` option in `createEventSource`.","cause":"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.","error":"TypeError: fetch is not a function"},{"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.","cause":"Incorrect import statement (e.g., using `require()` for a package primarily designed for ESM, or wrong named import syntax in CJS context).","error":"TypeError: createEventSource is not a function"},{"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.","cause":"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.","error":"TypeError: (intermediate value) is not async iterable"}],"ecosystem":"npm"}