Skip to content

An easy API for making Event Source requests, with all the features of fetch(), Supports browsers and node.js

License

Notifications You must be signed in to change notification settings

yokingma/fetch-sse

Folders and files

NameName
Last commit message
Last commit date

Latest commit

01d3b23 · Feb 20, 2025

History

64 Commits
Mar 15, 2024
Feb 20, 2025
Feb 20, 2025
Feb 20, 2025
Mar 15, 2024
Dec 20, 2024
Mar 8, 2024
Jan 6, 2025
Dec 20, 2024
Feb 20, 2025
Mar 16, 2024
Dec 20, 2024

Repository files navigation

Fetch SSE (Server-Sent Events)

This package provides an easy API for making Event Source requests with all the features of Fetch API, and supports browsers and Node.js.

For Node.js, v18.0.0 or higher required.

Install

npm install fetch-sse

Usage

import { fetchEventData } from 'fetch-sse';

await fetchEventData('/api/sse', {
  method: 'POST',
  data: { foo: 'bar' },
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  onMessage: (event) => {
    console.log(event);
  }
})

You can pass in other parameters in a similar way to the Fetch API.

import { fetchEventData } from 'fetch-sse';

await fetchEventData('/api/sse', {
  method: 'POST',
  // or JSON.stringify({ foo: 'bar' })
  data: { foo: 'bar' },
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  signal: ctrl.signal,
  onMessage: (event) => {
    console.log(event.data);
  }
})

Interface

// fetch options
export interface IFetchOptions {
  method?: string;
  headers?: HeadersInit | Record<string, any>;
  data?: BodyInit | Record<string, any> | null;
  signal?: AbortSignal;
  onMessage?: (event: ServerSentEvent | null, done?: boolean) => void;
  onOpen?: (res?: Response) => void;
  onClose?: () => void;
  onError?: (error: any) => void;
}

// decoded event
export interface ServerSentEvent {
  event: string | null;
  data: string;
  raw: string[];
}

Event stream pattern

The event stream is a simple stream of text data that encoded using UTF-8. You can find more information here.

  • Data-only messages

raw:


data: {"username": "bobby", "time": "02:33:48"}\n\n

parsed:

{
  event: null,
  data: '{"username": "bobby", "time": "02:33:48"}',
  raw: [
    'data: {"username": "bobby", "time": "02:33:48"}'
  ]
}
  • Named events

raw:

:HTTP\n
id: 1\n
event: result\n
data: {"username": "bobby", "time": "02:33:48"}\n\n

parsed:

{
  event: 'result',
  data: {"username": "bobby", "time": "02:33:48"},
  raw: [
    ':HTTP',
    'id: 1',
    'event: result',
    'data: {"username": "bobby", "time": "02:33:48"}'
  ]
}

Compatibility

this package is written in typescript and compatible with browsers and nodejs, You might need to polyfill TextDecoder for old versions of browsers.

About

An easy API for making Event Source requests, with all the features of fetch(), Supports browsers and node.js

Resources

License

Stars

Watchers

Forks