Parse Server-Sent Events

0.1.0 · active · verified Tue Apr 21

`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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { parseServerSentEvents } from 'parse-sse';

const apiKey = process.env.OPENAI_API_KEY ?? 'YOUR_OPENAI_API_KEY_HERE';

async function getStreamingCompletion() {
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      model: 'gpt-4',
      messages: [{ role: 'user', content: 'Tell me a story about a futuristic city.' }],
      stream: true,
    }),
  });

  if (!response.body) {
    throw new Error('Response body is null, expected a ReadableStream.');
  }

  console.log('--- Streaming Chat Completion ---\n');
  for await (const event of parseServerSentEvents(response)) {
    if (event.data === '[DONE]') {
      console.log('\n--- Stream Ended ---');
      break;
    }

    try {
      const data = JSON.parse(event.data);
      process.stdout.write(data.choices[0]?.delta?.content || '');
    } catch (error) {
      console.error('Error parsing event data:', event.data, error);
    }
  }
}

getStreamingCompletion().catch(console.error);

view raw JSON →