{"id":10854,"library":"eventsource-parser","title":"EventSource/Server-Sent Events Parser","description":"eventsource-parser is a highly performant and source-agnostic streaming parser for Server-Sent Events (SSE) / EventSource data. It does not assume how the data stream is obtained, making it a versatile building block for various JavaScript environments like browsers, Node.js, and Deno. The current stable version is 3.0.7, with frequent releases addressing bug fixes, performance improvements, and ongoing maintenance. Key differentiators include its streaming nature, a `TransformStream` variant for modern environments, and its role as a low-level parser that can be integrated into custom networking stacks or clients, contrasting with higher-level clients like `eventsource-client` or Node.js polyfills like `eventsource`.","status":"active","version":"3.0.7","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/rexxars/eventsource-parser","tags":["javascript","eventsource","server-sent-events","sse","typescript"],"install":[{"cmd":"npm install eventsource-parser","lang":"bash","label":"npm"},{"cmd":"yarn add eventsource-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add eventsource-parser","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Since v3.0.0, `createParser` is a named export. Default imports are no longer supported. The package is ESM-only in recent major versions.","wrong":"import createParser from 'eventsource-parser'","symbol":"createParser","correct":"import { createParser } from 'eventsource-parser'"},{"note":"This is a type definition for the parsed event object, best imported using `import type`. It was renamed from `ParsedEvent` in v3.0.0.","wrong":"import { EventSourceMessage } from 'eventsource-parser'","symbol":"EventSourceMessage","correct":"import type { EventSourceMessage } from 'eventsource-parser'"},{"note":"The `TransformStream` variant is exposed under a separate import path to ensure compatibility with environments that may not support `TransformStream` natively.","wrong":"import { EventSourceParserStream } from 'eventsource-parser'","symbol":"EventSourceParserStream","correct":"import { EventSourceParserStream } from 'eventsource-parser/stream'"}],"quickstart":{"code":"import { createParser, type EventSourceMessage, type ParseError } from 'eventsource-parser';\n\n// Simulate a readable stream, e.g., from a fetch response body\nasync function getSimulatedSseStream(): Promise<ReadableStreamDefaultReader<Uint8Array>> {\n  const sseData = `id: 1\\nevent: message\\ndata: Hello, world!\\n\\nretry: 5000\\nid: 2\\ndata: Another message\\n\\n`;\n  const encoder = new TextEncoder();\n  const stream = new ReadableStream<Uint8Array>({\n    start(controller) {\n      controller.enqueue(encoder.encode(sseData.substring(0, 20)));\n      setTimeout(() => {\n        controller.enqueue(encoder.encode(sseData.substring(20, 50)));\n      }, 100);\n      setTimeout(() => {\n        controller.enqueue(encoder.encode(sseData.substring(50)));\n        controller.close();\n      }, 200);\n    },\n  });\n  return stream.getReader();\n}\n\nasync function parseSseStream() {\n  let retryInterval = 3000;\n\n  const parser = createParser({\n    onEvent(event: EventSourceMessage) {\n      console.log('Received event:');\n      console.log('  id:', event.id || '<none>');\n      console.log('  event:', event.event || '<none>');\n      console.log('  data:', event.data);\n    },\n    onRetry(interval: number) {\n      console.log('Server requested retry interval of %dms', interval);\n      retryInterval = interval;\n    },\n    onError(error: ParseError) {\n      console.error('Error parsing event stream:', error.message);\n      if (error.type === 'invalid-retry') {\n        console.error('Invalid retry value:', error.value);\n      }\n    }\n  });\n\n  const sseStreamReader = await getSimulatedSseStream();\n\n  try {\n    while (true) {\n      const { done, value } = await sseStreamReader.read();\n      if (done) break;\n      parser.feed(new TextDecoder().decode(value));\n    }\n  } finally {\n    parser.reset({ consume: true }); // Important: flush any pending data and reset state\n  }\n  console.log('Stream parsing complete. Last known retry interval:', retryInterval);\n}\n\nparseSseStream().catch(console.error);","lang":"typescript","description":"This example demonstrates how to create and use the `eventsource-parser` to process a simulated Server-Sent Events stream, handle parsed events, process retry interval directives, and catch parsing errors. It showcases the new callback-based API introduced in v3."},"warnings":[{"fix":"Migrate your parser initialization to `createParser({ onEvent, onRetry, onError })` and update type references from `ParsedEvent` to `EventSourceMessage`. Refer to the official migration guide for a complete overview.","message":"Version 3.0.0 introduced significant breaking changes to the parser's API. Instead of a single `onParse` callback that required type checking, `createParser` now expects an object of callbacks (`onEvent`, `onRetry`, `onError`, `onComment`) for specific event types. The `ParsedEvent` type was also renamed to `EventSourceMessage`, and its `type` attribute was removed.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Ensure your Node.js environment is version 18 or higher. If you need to support older Node.js versions, you must stick to `eventsource-parser` v1.x.","message":"As of version 2.0.0, the minimum supported Node.js version is Node.js 18. This change was introduced to leverage modern Web Streams and `fetch` API capabilities.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always call `parser.reset({ consume: true })` within a `finally` block or after confirming the stream's completion, especially when reusing a parser instance.","message":"When consuming a stream, it's crucial to call `parser.reset({ consume: true })` after the stream ends or an error occurs. This flushes any remaining buffered data and resets the parser's internal state. Failing to do so might prevent the last incomplete event from being processed or leave the parser in an inconsistent state.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For the `TransformStream` variant, always import from `eventsource-parser/stream` to ensure stability across patch versions and clarity on module intent. For the main parser, use named ESM imports.","message":"In versions 3.0.2 and 3.0.3, there were changes and reintroductions of legacy module exports. While v3.0.2 dropped a legacy module export, v3.0.3 specifically reintroduced legacy exports for the `stream` module. This could lead to inconsistent import behavior depending on the exact patch version and target environment.","severity":"gotcha","affected_versions":"3.0.2, 3.0.3"},{"fix":"Ensure you are passing an object with `onEvent`, `onRetry`, `onError` (and optionally `onComment`) callbacks to `createParser`, not a single function. For example: `createParser({ onEvent: (event) => {...} })`.","message":"The `createParser` function will throw a helpful error if you mistakenly pass a function directly to it instead of an object of callbacks, particularly since the v3 API change. This indicates a misuse of the updated API.","severity":"gotcha","affected_versions":">=3.0.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Use a named import: `import { createParser } from 'eventsource-parser'`. For CommonJS environments, consider a tool like `esm` or ensure your build process correctly handles ESM imports. If passing a function directly, wrap it in an object for the `onEvent` callback: `createParser({ onEvent: myEventHandler })`.","cause":"Attempting to use `createParser` as a default import (e.g., `import createParser from '...'`) or via `require()` in a CommonJS environment, which is no longer supported since v3.0.0 which moved to named exports and ESM-first. Alternatively, passing a function directly to `createParser` instead of an options object in v3+ can also lead to similar runtime issues.","error":"TypeError: createParser is not a function"},{"fix":"Ensure you import it as a type: `import type { EventSourceMessage } from 'eventsource-parser'`. If you are on an older version, use `ParsedEvent` instead.","cause":"This error typically occurs if `EventSourceMessage` is used as a type but not correctly imported as a type, or if an older version of the parser (v1.x/v2.x) used `ParsedEvent` instead, which was renamed in v3.0.0.","error":"ReferenceError: EventSourceMessage is not defined"},{"fix":"Upgrade your Node.js runtime to version 18 or newer, or downgrade `eventsource-parser` to v1.x if older Node.js versions are required.","cause":"Running `eventsource-parser` v2.0.0 or higher in a Node.js environment older than v18.","error":"UnhandledPromiseRejectionWarning: TypeError: Invalid minimum Node.js version"}],"ecosystem":"npm"}