Server-Sent Events with Fetch API

0.1.6 · active · verified Sun Apr 19

fetch-event-stream is a lightweight (741 bytes gzipped) utility designed to parse Server-Sent Events (SSE) from `fetch` responses using the native Web Streams API. It's currently at version 0.1.6 and has a frequent patch release cadence, addressing compatibility and feature enhancements. Unlike the browser's native `EventSource` which is limited to GET requests and lacks custom headers, `fetch-event-stream` allows any HTTP method (e.g., POST for APIs like Anthropic or OpenAI) and supports custom headers and JSON payloads, making it suitable for modern API interactions that often require authentication. It differentiates itself by leveraging native Web Streams without heavy polyfills, ensuring a small bundle size and broad compatibility across browsers, Node.js, Deno, Bun, Cloudflare Workers, and Web/Service Workers. This approach avoids the common pain point of bloated SDKs, such as the `openai` library's larger size due to stream polyfills, offering a more streamlined and performant solution for SSE consumption.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to a streaming OpenAI API endpoint using the `stream` utility, handling API keys, request body, and iterating over Server-Sent Events.

import { stream } from 'fetch-event-stream';

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

async function getOpenAIStream() {
  try {
    const events = await stream('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${OPENAI_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          { role: 'system', content: 'You are a helpful assistant.' },
          { role: 'user', content: 'What is the capital of France?' }
        ],
        stream: true
      })
    });

    for await (const event of events) {
      if (event.data === '[DONE]') {
        console.log('Stream finished.');
        break;
      }
      try {
        const parsedData = JSON.parse(event.data);
        // Process your parsed SSE data here
        console.log('Received:', parsedData);
      } catch (e) {
        console.error('Failed to parse event data:', event.data, e);
      }
    }
  } catch (error) {
    if (error instanceof Response) {
      const errorText = await error.text();
      console.error('API Error:', error.status, errorText);
    } else {
      console.error('An unexpected error occurred:', error);
    }
  }
}

getOpenAIStream();

view raw JSON →