{"id":13160,"library":"event-stream-parser","title":"Server-Sent Events Parser","description":"The `event-stream-parser` package provides a lightweight, zero-dependency implementation for parsing Server-Sent Events (SSE) streams, strictly adhering to the HTML Living Standard specification. Designed to leverage the Web Streams API, it offers full compatibility with modern web browsers and Node.js environments (requiring Node.js >=18.0.0). The current stable version is `1.0.2`, with a release cadence that has been fairly rapid since its initial v1.0.0 release in early 2024. Its key differentiators include its minimalistic design, native Web Streams integration for efficient processing, and comprehensive TypeScript support, making it an ideal choice for applications requiring robust and standards-compliant SSE consumption without external bloat.","status":"active","version":"1.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/KEY60228/event-stream-parser","tags":["javascript","sse","server-sent-events","parser","stream","streaming","eventsource","typescript"],"install":[{"cmd":"npm install event-stream-parser","lang":"bash","label":"npm"},{"cmd":"yarn add event-stream-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add event-stream-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The `parse` function is a named export. Default imports will not work. This package is ESM-only.","wrong":"import parse from 'event-stream-parser';","symbol":"parse","correct":"import { parse } from 'event-stream-parser';"},{"note":"Explicitly importing from '/v1' is supported. CommonJS `require()` syntax is not supported as the package is ESM-only.","wrong":"const { parse } = require('event-stream-parser');","symbol":"parse","correct":"import { parse } from 'event-stream-parser/v1';"},{"note":"For type-checking in TypeScript, import the `MessageEvent` type if you need to explicitly type stream events.","symbol":"MessageEvent (type)","correct":"import type { MessageEvent } from 'event-stream-parser';"}],"quickstart":{"code":"import { parse } from 'event-stream-parser';\n\nasync function fetchAndParseEvents() {\n  const sseApiUrl = process.env.SSE_API_URL ?? 'https://demo.vercel.events/api/kitchensink'; // Example SSE endpoint\n\n  try {\n    const response = await fetch(sseApiUrl, {\n      headers: {\n        'Accept': 'text/event-stream',\n        'Cache-Control': 'no-cache',\n        'Connection': 'keep-alive'\n      },\n    });\n\n    if (!response.ok) {\n      throw new Error(`HTTP error! Status: ${response.status}`);\n    }\n\n    if (!response.body) {\n      throw new Error('Response body is null; server might not be sending a stream.');\n    }\n\n    console.log(`Connected to SSE stream at ${sseApiUrl}`);\n    const eventStream = await parse(response.body);\n\n    await eventStream.pipeTo(\n      new WritableStream<MessageEvent>({\n        write(event) {\n          console.log('\\n--- Event Received ---');\n          console.log(`Type: ${event.type || '[default]'}`);\n          console.log(`Data: ${event.data}`);\n          if (event.lastEventId) {\n            console.log(`Last Event ID: ${event.lastEventId}`);\n          }\n        },\n        close() {\n          console.log('\\n--- Event Stream Closed ---');\n        },\n        abort(reason) {\n          console.error('\\n--- Event Stream Aborted ---', reason);\n        }\n      })\n    );\n  } catch (error) {\n    console.error('Failed to fetch or process event stream:', error);\n  }\n}\n\nfetchAndParseEvents();","lang":"typescript","description":"Demonstrates how to fetch a Server-Sent Events stream using `fetch`, parse it with `event-stream-parser`, and consume the resulting `MessageEvent` objects via a `WritableStream`."},"warnings":[{"fix":"Use `const eventStream = await parse(response.body);` instead of `const eventStream = parse(response.body);`","message":"The `parse` function returns a `Promise<ReadableStream<MessageEvent>>`, not directly a `ReadableStream`. Ensure you `await` the result of `parse` before attempting to pipe or read from the event stream.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade your Node.js environment to version 18 or newer (e.g., `nvm install 18 && nvm use 18`).","message":"This package requires Node.js version 18.0.0 or higher due to its reliance on modern Web Streams API features and ESM module system. Running on older Node.js versions will result in compatibility errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your `fetch` request includes `{ headers: { Accept: 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' } }`.","message":"When using `fetch` to consume an SSE stream, it is crucial to set the `Accept: 'text/event-stream'` header. Additionally, `Cache-Control: 'no-cache'` and `Connection: 'keep-alive'` are often necessary for proper streaming behavior, although not strictly required by the parser itself.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use `import { parse } from 'event-stream-parser';` for importing. Ensure your Node.js version is >=18 and your project is configured for ESM (e.g., `\"type\": \"module\"` in `package.json`).","cause":"Attempting to use CommonJS `require()` syntax in an ESM-only project, or an older Node.js environment that does not fully support ESM.","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Verify the server endpoint is correctly configured to send Server-Sent Events, and ensure your `fetch` request includes the `Accept: 'text/event-stream'` header.","cause":"The `fetch` API returned a response without a readable body, which can happen if the server did not respond with a stream, or if the `Content-Type` was not `text/event-stream` as expected.","error":"TypeError: response.body is null"},{"fix":"Always `await` the result of the `parse` function: `const eventStream = await parse(response.body);`.","cause":"This error occurs if you try to call `.pipeTo()` on the `Promise` returned by `parse()` instead of on the `ReadableStream` it resolves to.","error":"TypeError: (intermediate value).pipeTo is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}