Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

eventsource

EventSource13.5mMIT3.0.2TypeScript support: included

WhatWG/W3C compliant EventSource client for Node.js and browsers

sse, eventsource, server-sent-events

readme

eventsource

npm versionnpm bundle sizenpm weekly downloads

WhatWG/W3C-compatible server-sent events/eventsource client. The module attempts to implement an absolute minimal amount of features/changes beyond the specification.

If you're looking for a modern alternative with a less constrained API, check out the eventsource-client package.

Installation

npm install --save eventsource

Supported engines

  • Node.js >= 18
  • Chrome >= 63
  • Safari >= 11.3
  • Firefox >= 65
  • Edge >= 79
  • Deno >= 1.30
  • Bun >= 1.1.23

Basically, any environment that supports:

If you need to support older runtimes, try the 2.x branch/version range (note: 2.x branch is primarily targetted at Node.js, not browsers).

Usage

import {EventSource} from 'eventsource'

const es = new EventSource('https://my-server.com/sse')

/*
 * This will listen for events with the field `event: notice`.
 */
es.addEventListener('notice', (event) => {
  console.log(event.data)
})

/*
 * This will listen for events with the field `event: update`.
 */
es.addEventListener('update', (event) => {
  console.log(event.data)
})

/*
 * The event "message" is a special case, as it will capture events _without_ an
 * event field, as well as events that have the specific type `event: message`.
 * It will not trigger on any other event type.
 */
es.addEventListener('message', (event) => {
  console.log(event.data)
})

/**
 * To explicitly close the connection, call the `close` method.
 * This will prevent any reconnection from happening.
 */
setTimeout(() => {
  es.close()
}, 10_000)

Migrating from v1 / v2

See MIGRATION.md for a detailed migration guide.

Extensions to the WhatWG/W3C API

Message and code properties on errors

The error event has a message and code property that can be used to get more information about the error. In the specification, the Event

es.addEventListener('error', (err) => {
  if (err.code === 401 || err.code === 403) {
    console.log('not authorized')
  }
})

Specify fetch implementation

The EventSource constructor accepts an optional fetch property in the second argument that can be used to specify the fetch implementation to use.

This can be useful in environments where the global fetch function is not available - but it can also be used to alter the request/response behaviour.

Setting HTTP request headers

const es = new EventSource('https://my-server.com/sse', {
  fetch: (input, init) =>
    fetch(input, {
      ...init,
      headers: {
        ...init.headers,
        Authorization: 'Bearer myToken',
      },
    }),
})

HTTP/HTTPS proxy

Use a package like node-fetch-native to add proxy support, either through environment variables or explicit configuration.

// npm install node-fetch-native --save
import {fetch} from 'node-fetch-native/proxy'

const es = new EventSource('https://my-server.com/sse', {
  fetch: (input, init) => fetch(input, init),
})

Allow unauthorized HTTPS requests

Use a package like undici for more control of fetch options through the use of an Agent.

// npm install undici --save
import {fetch, Agent} from 'undici'

await fetch('https://my-server.com/sse', {
  dispatcher: new Agent({
    connect: {
      rejectUnauthorized: false,
    },
  }),
})

License

MIT-licensed. See LICENSE.

changelog

📓 Changelog

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

3.0.2 (2024-12-13)

Bug Fixes

  • reference possibly missing event typings (d3b6849)

3.0.1 (2024-12-07)

Bug Fixes

  • run build prior to publishing (f86df19)

3.0.0 (2024-12-07)

⚠ BREAKING CHANGES

  • Drop support for Node.js versions below v18
  • The module now uses a named export instead of a default export.
  • UMD bundle dropped. Use a bundler.
  • headers in init dict dropped, pass a custom fetch function instead.
  • HTTP/HTTPS proxy support dropped. Pass a custom fetch function instead.
  • https.* options dropped. Pass a custom fetch function that provides an agent/dispatcher instead.
  • New default reconnect delay: 3 seconds instead of 1 second.
  • Reconnecting after a redirect will now always use the original URL, even if the status code was HTTP 307.

Features

  • modernize - use fetch, WebStreams, TypeScript, ESM (#330) (40655f7)

Bug Fixes

  • dispatchEvent now emits entire event object (eb430c0)
  • empty options no longer disable certificate checks (372d387)

2.0.2 (2022-05-12)

Bug Fixes

  • strip sensitive headers on redirect to different origin (10ee0c4)

2.0.1 (2022-04-25)

Bug Fixes

  • Fix URL is not a constructor error for browser (#268 Ajinkya Rajput)

2.0.0 (2022-03-02)

⚠ BREAKING CHANGES

  • Node >= 12 now required (#152 @HonkingGoose)

Bug Fixes

  • Preallocate buffer size when reading data for increased performance with large messages (#239 Pau Freixes)
  • Removed dependency on url-parser. Fixes CVE-2022-0512 & CVE-2022-0691 (#249 Alex Hladin)

Bug Fixes

  • NPM download badge links to malware (8954d63)

1.1.2 (2022-06-08)

Features

  • Inline origin resolution, drops original dependency (#281 Espen Hovlandsdal)

1.1.1 (2022-05-11)

Bug Fixes

  • Do not include authorization and cookie headers on redirect to different origin (#273 Espen Hovlandsdal)

1.1.0 (2021-03-18)

Features

  • Improve performance for large messages across many chunks (#130 Trent Willis)
  • Add createConnection option for http or https requests (#120 Vasily Lavrov)
  • Support HTTP 302 redirects (#116 Ryan Bonte)

Bug Fixes

  • Prevent sequential errors from attempting multiple reconnections (#125 David Patty)
  • Add new to correct test (#111 Stéphane Alnet)
  • Fix reconnections attempts now happen more than once (#136 Icy Fish)

1.0.7 (2018-08-27)

Features

  • Add dispatchEvent to EventSource (#101 Ali Afroozeh)
  • Added checkServerIdentity option (#104 cintolas)
  • Surface request error message (#107 RasPhilCo)

1.0.6 (2018-08-23)

Bug Fixes

  • Fix issue where a unicode sequence split in two chunks would lead to invalid messages (#108 Espen Hovlandsdal)

1.0.5 (2017-07-18)

Bug Fixes

  • Check for window existing before polyfilling. (#80 Neftaly Hernandez)

1.0.4 (2017-06-19)

Bug Fixes

  • Pass withCredentials on to the XHR. (#79 Ken Mayer)

1.0.2 (2017-05-28)

Bug Fixes

  • Fix proxy not working when proxy and target URL uses different protocols. (#76 Espen Hovlandsdal)
  • Make close() a prototype method instead of an instance method. (#77 Espen Hovlandsdal)

1.0.1 (2017-05-10)

Bug Fixes

  • Reconnect if server responds with HTTP 500, 502, 503 or 504. (#74 Vykintas Narmontas)

1.0.0 (2017-04-17)

Features

  • Add missing removeEventListener-method. (#51 Yucheng Tu / Espen Hovlandsdal)
  • Add ability to customize https options. (#53 Rafael Alfaro)
  • Add readyState constants to EventSource instances. (#66 Espen Hovlandsdal)

Bug Fixes

  • Fix EventSource reconnecting on non-200 responses. (af84476 Espen Hovlandsdal)

0.2.3 (2017-04-17)

Bug Fixes

  • Fix onConnectionClosed firing multiple times resulting in multiple connections. (#61 Phil Strong / Duncan Wong)

Reverts

  • Revert "Protects against multiple connects" (3887a4a)

0.2.2 (2017-02-28)

Bug Fixes

  • Don't include test files in npm package. (#56 eanplatter)

0.2.1 (2016-02-28)

Features

  • Add http/https proxy function. (#46 Eric Lu)
  • Drop support for Node 0.10.x and older (Aslak Hellesøy).

Bug Fixes

  • Fix close() for polyfill. (#52 brian-medendorp)
  • Fix reconnect for polyfill. Only disable reconnect when server status is 204. (Aslak Hellesøy).

0.2.0 (2016-02-11)

Features

  • Renamed repository to eventsource (since it's not just Node, but also browser polyfill). (Aslak Hellesøy).
  • Compatibility with webpack/browserify. (#44 Adriano Raiano).

0.1.6 (2015-02-09)

Bug Fixes

  • Ignore headers without a value. (#41, #43 Adriano Raiano)

0.1.5 (2015-02-08)

Features

  • Refactor tests to support Node.js 0.12.0 and Io.js 1.1.0. (Aslak Hellesøy)

0.1.4 (2014-10-31)

Features

  • Expose status property on error events. (#40 Adriano Raiano)

Bug Fixes

  • Added missing origin property. (#39, #38 Arnout Kazemier)

0.1.3 (2014-09-17)

Bug Fixes

  • Made message properties enumerable. (#37 Golo Roden)

0.1.2 (2014-08-07)

Bug Fixes

  • Blank lines not read. (#35, #36 Lesterpig)

0.1.1 (2014-05-18)

Bug Fixes

  • Fix message type. (#33 Romain Gauthier)

0.1.0 (2014-03-07)

Bug Fixes

  • High CPU usage by replacing Jison with port of WebKit's parser. (#25, #32, #18 qqueue)

0.0.10 (2013-11-21)

Features

  • Provide Event argument on open and error event (#30, #31 Donghwan Kim)
  • Expose lastEventId on messages. (#28 mbieser)

0.0.9 (2013-10-24)

Bug Fixes

  • Old "last-event-id" used on reconnect (#27 Aslak Hellesøy)

0.0.8 (2013-09-12)

Features

  • Allow unauthorized HTTPS connections by setting rejectUnauthorized to false. (Aslak Hellesøy)

Bug Fixes

  • EventSource still reconnected when closed (#24 FrozenCow)

0.0.7 (2013-04-19)

Features

  • Explicitly raise an error when server returns http 403 and don't continue (#20 Scott Moak)
  • Added ability to send custom http headers to server (#21, #9 Scott Moak)
  • Switched from testing with Nodeunit to Mocha (Aslak Hellesøy)

Bug Fixes

  • Fix Unicode support to cope with Javascript Unicode size limitations (#23, #22 Devon Adkisson)
  • Graceful handling of parse errors (#19 Aslak Hellesøy)

0.0.6 (2013-01-24)

Features

  • Add Accept: text/event-stream header (#17 William Wicks)

0.0.5 (2012-02-12)

Features

  • Add no-cache and https support (#10 Einar Otto Stangvik)
  • Ensure that Last-Event-ID is sent to the server for reconnects, as defined in the spec (#8 Einar Otto Stangvik)
  • Verify that CR and CRLF are accepted alongside LF (#7 Einar Otto Stangvik)
  • Emit 'open' event (#4 Einar Otto Stangvik)

0.0.4 (2012-02-10)

Features

  • Automatic reconnect every second if the server is down. Reconnect interval can be set with reconnectInterval (not in W3C spec). (Aslak Hellesøy)

0.0.3 (2012-02-10)

Features

  • Jison based eventstream parser (#2 Einar Otto Stangvik)

0.0.2 (2012-02-08)

Features

  • Use native EventListener (Aslak Hellesøy)

0.0.1 (2012-02-08)

Features

  • First release (Aslak Hellesøy)