{"id":16168,"library":"parse-sse","title":"Parse Server-Sent Events","description":"`parse-sse` is a lightweight, spec-compliant JavaScript library designed for parsing Server-Sent Events (SSE) from a standard Web `Response` object, typically obtained via the native Fetch API. Currently at version 0.1.0, it is a new release focused on providing a robust and efficient way to consume streaming APIs. The library differentiates itself by being fully compatible with native `ReadableStream` and `TransformStream` interfaces, enabling maximum composability with other stream-based operations. It is particularly well-suited for integrating with modern streaming services like OpenAI and Anthropic, which extensively utilize SSE for real-time data delivery. As a relatively new package, a specific release cadence has not yet been established, but its focus on web platform standards and minimal dependencies suggests a stable foundation.","status":"active","version":"0.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/sindresorhus/parse-sse","tags":["javascript","sse","server-sent-events","eventsource","event-stream","parse","parser","stream","streaming","typescript"],"install":[{"cmd":"npm install parse-sse","lang":"bash","label":"npm"},{"cmd":"yarn add parse-sse","lang":"bash","label":"yarn"},{"cmd":"pnpm add parse-sse","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"`parse-sse` is an ESM-only package, requiring `import` syntax. Attempting to use `require()` will result in a runtime error.","wrong":"const { parseServerSentEvents } = require('parse-sse');","symbol":"parseServerSentEvents","correct":"import { parseServerSentEvents } from 'parse-sse';"},{"note":"This named export is for advanced stream pipeline construction. Like all exports from `parse-sse`, it's ESM-only.","wrong":"const { ServerSentEventTransformStream } = require('parse-sse');","symbol":"ServerSentEventTransformStream","correct":"import { ServerSentEventTransformStream } from 'parse-sse';"}],"quickstart":{"code":"import { parseServerSentEvents } from 'parse-sse';\n\nconst apiKey = process.env.OPENAI_API_KEY ?? 'YOUR_OPENAI_API_KEY_HERE';\n\nasync function getStreamingCompletion() {\n  const response = await fetch('https://api.openai.com/v1/chat/completions', {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json',\n      'Authorization': `Bearer ${apiKey}`,\n    },\n    body: JSON.stringify({\n      model: 'gpt-4',\n      messages: [{ role: 'user', content: 'Tell me a story about a futuristic city.' }],\n      stream: true,\n    }),\n  });\n\n  if (!response.body) {\n    throw new Error('Response body is null, expected a ReadableStream.');\n  }\n\n  console.log('--- Streaming Chat Completion ---\\n');\n  for await (const event of parseServerSentEvents(response)) {\n    if (event.data === '[DONE]') {\n      console.log('\\n--- Stream Ended ---');\n      break;\n    }\n\n    try {\n      const data = JSON.parse(event.data);\n      process.stdout.write(data.choices[0]?.delta?.content || '');\n    } catch (error) {\n      console.error('Error parsing event data:', event.data, error);\n    }\n  }\n}\n\ngetStreamingCompletion().catch(console.error);","lang":"typescript","description":"Demonstrates how to consume a streaming chat completion from OpenAI using `parse-sse` with the Fetch API, showing real-time output and handling the `[DONE]` signal."},"warnings":[{"fix":"Ensure your project runs on Node.js 20+ and uses ES module syntax (`import`/`export`). For CommonJS projects, consider using a tool like `esm` or migrating to ESM.","message":"`parse-sse` is an ESM-only package and explicitly requires Node.js version 20 or higher. Older Node.js versions or CommonJS environments are not supported.","severity":"breaking","affected_versions":"<=0.1.0"},{"fix":"Pipe your byte stream through `new TextDecoderStream()` before `ServerSentEventTransformStream`, e.g., `response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new ServerSentEventTransformStream())`.","message":"When using `ServerSentEventTransformStream` directly, the input stream is expected to consist of string chunks. If you are piping from a raw byte stream (e.g., `response.body`), you must pipe through a `TextDecoderStream` first to ensure proper Unicode decoding and chunk handling.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Always serialize complex data (like multi-line strings or objects) within the `data` field as JSON, and then parse it on the client side, e.g., `JSON.parse(event.data)`. This ensures proper handling of internal newlines.","message":"Server-Sent Events are processed based on `\\n\\n` delimiters. If your `data` field contains literal newline characters that are *not* part of a JSON string or properly escaped, it can lead to misinterpretation by the parser, breaking multi-line data.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Change `const { parseServerSentEvents } = require('parse-sse');` to `import { parseServerSentEvents } from 'parse-sse';` and ensure your `package.json` has `\"type\": \"module\"` or your file has `.mjs` extension.","cause":"Attempting to use CommonJS `require()` syntax in an ES module environment, which `parse-sse` exclusively supports.","error":"ReferenceError: require is not defined"},{"fix":"Verify that your environment is set up for ES modules (Node.js 20+ and correct `package.json` `type` field) and that you are using `import { parseServerSentEvents } from 'parse-sse';`.","cause":"Incorrectly importing the `parseServerSentEvents` function, often due to a mixed CommonJS/ESM environment issue or incorrect named import.","error":"TypeError: parseServerSentEvents is not a function"},{"fix":"Ensure the server is actually sending a stream (`Content-Type: text/event-stream`) and the `response.ok` is true. Handle cases where `response.body` might be `null` or already consumed before passing it to `parseServerSentEvents`.","cause":"The `Response` object from `fetch` did not contain a readable body, possibly due to a non-streaming response type, an error status, or the body already being consumed.","error":"Error: Response body is null"},{"fix":"Prepend a `TextDecoderStream` to the pipeline: `response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new ServerSentEventTransformStream())`.","cause":"`ServerSentEventTransformStream` received byte chunks (e.g., from `response.body`) instead of decoded string chunks.","error":"TypeError: If you pass byte chunks, a TypeError will be thrown."}],"ecosystem":"npm"}