Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/nodejs/undici/llms.txt

Use this file to discover all available pages before exploring further.

undici exports an EventSource class that implements the WHATWG EventSource API for receiving server-sent events (SSE) in Node.js. It supports custom dispatchers, making it possible to add authentication headers, route through proxies, or configure TLS — capabilities not available in browser EventSource.
The EventSource implementation is experimental and may change in future versions.

Constructor

new EventSource(url[, options])
url
string | URL
required
The URL of the SSE endpoint. Must be HTTP or HTTPS.
options
EventSourceInit
Optional configuration object.

Basic usage

Receiving server-sent events
import { EventSource } from 'undici'

const eventSource = new EventSource('http://localhost:3000/events')

eventSource.onmessage = (event) => {
  console.log('Message:', event.data)
}

eventSource.addEventListener('update', (event) => {
  console.log('Update event:', event.data)
})

eventSource.onerror = (event) => {
  console.error('EventSource error:', event)
}

Using a custom dispatcher

Pass a custom dispatcher to add headers, use a proxy, or configure TLS:
Custom headers via dispatcher
import { EventSource, Agent } from 'undici'

class AuthenticatedAgent extends Agent {
  dispatch(opts, handler) {
    opts.headers = {
      ...opts.headers,
      'authorization': 'Bearer my-token',
      'x-custom-header': 'value'
    }
    return super.dispatch(opts, handler)
  }
}

const eventSource = new EventSource('http://localhost:3000/events', {
  dispatcher: new AuthenticatedAgent()
})

eventSource.onmessage = (event) => {
  console.log(event.data)
}

Properties

readyState
number
Current connection state: 0 (CONNECTING), 1 (OPEN), or 2 (CLOSED).
url
string
The URL of the event source.
withCredentials
boolean
Whether the connection was created with credentials.

Event handlers

HandlerFires when
onopenConnection is established
onmessageA message event with no event field is received
onerrorAn error occurs or the connection is lost
Named events use addEventListener:
eventSource.addEventListener('ping', (event) => {
  console.log('Ping received:', event.data)
  console.log('Event ID:', event.lastEventId)
})

Closing the connection

eventSource.close()
The connection is permanently closed and will not reconnect.

SSE message format

The server must respond with Content-Type: text/event-stream. Each message follows the SSE format:
data: Hello, world!\n\n

event: update
data: {"count": 42}\n\n

id: 123
data: Message with ID\n\n
For more details on the EventSource API, see MDN EventSource.

Build docs developers (and LLMs) love