EventSource is a WHATWG-conformant implementation of the
server-sent events interface. It opens a persistent HTTP connection to a
server that responds with the text/event-stream content type and dispatches
the events it receives without closing the connection.
import { EventSource } from 'undici'
const eventSource = new EventSource('http://localhost:3000')
eventSource.onmessage = (event) => {
console.log(event.data)
}Constructing an EventSource for the first time emits a one-time
ExperimentalWarning with the code 'UNDICI-ES'. The interface is also
installed onto globalThis as globalThis.EventSource.
class EventSource extends EventTargetThe EventSource interface receives server-sent events over an HTTP
connection. Instances are created with the new EventSource()
constructor and emit 'open', 'message', and
'error' events.
new EventSource(url, eventSourceInitDict?): void<Object><boolean>true
, the request is made with the
credentials mode set to
include
and CORS attribute state set to
use-credentials
; otherwise the credentials mode is
same-origin
.
Default:
false
.<Dispatcher><Object>EventSourceInit
dictionary.<Dispatcher><number>retry
field.
Default:
3000
.Creates a new EventSource and immediately begins connecting to url. The
request is sent with the Accept: text/event-stream header, a cache mode of
no-store, and an initiator type of other.
If url cannot be parsed, a SyntaxError DOMException is thrown.
import { EventSource } from 'undici'
const eventSource = new EventSource('http://localhost:3000', {
withCredentials: true
})A custom Dispatcher can be supplied to control the underlying request, for
example to add request headers:
import { EventSource, Agent } from 'undici'
class CustomHeaderAgent extends Agent {
dispatch (opts) {
opts.headers['x-custom-header'] = 'hello world'
return super.dispatch(...arguments)
}
}
const eventSource = new EventSource('http://localhost:3000', {
node: {
dispatcher: new CustomHeaderAgent()
}
})eventSource.close(): undefined<undefined>Closes the connection, if any, aborts the underlying request, and sets
eventSource.readyState to CLOSED. Once closed, the
EventSource does not attempt to reconnect. Calling close() on an already
closed EventSource has no effect.
<number>A read-only number representing the state of the connection. It is one of the following constants:
EventSource.CONNECTING(0) — the connection has not yet been established, or it was closed and is being re-established.EventSource.OPEN(1) — the connection is open and events are being dispatched as they are received.EventSource.CLOSED(2) — the connection is not open and is not being re-established.
<string>A read-only string providing the URL of the event stream, after resolution against the environment's base URL.
<boolean>A read-only boolean indicating whether the EventSource was instantiated with
CORS credentials (true), or not (false, the default). It reflects the
withCredentials option passed to the constructor.
<Function>
|
<null>null
.An event handler that is invoked when an 'open' event is
dispatched. Assigning a function registers it as the handler; assigning null
removes the current handler.
<Function>
|
<null>null
.An event handler that is invoked when a 'message' event is
dispatched. Assigning a function registers it as the handler; assigning null
removes the current handler.
<Function>
|
<null>null
.An event handler that is invoked when an 'error' event is
dispatched. Assigning a function registers it as the handler; assigning null
removes the current handler.
<number>The numeric constant 0, representing the CONNECTING
readyState. It is defined as a read-only,
non-writable property on both the EventSource constructor and instances.
<number>The numeric constant 1, representing the OPEN
readyState. It is defined as a read-only,
non-writable property on both the EventSource constructor and instances.
<number>The numeric constant 2, representing the CLOSED
readyState. It is defined as a read-only,
non-writable property on both the EventSource constructor and instances.
Emitted when the connection is established and the
readyState becomes OPEN. The listener receives an
<Event>.
import { EventSource } from 'undici'
const eventSource = new EventSource('http://localhost:3000')
eventSource.addEventListener('open', () => {
console.log('connection opened')
})Emitted when a message that has no explicit event field is received. The
listener receives a <MessageEvent> whose data, lastEventId, and origin
properties are populated from the server-sent event. Named events (those with an
event field) are dispatched under their own type and must be subscribed to with
addEventListener().
import { createServer } from 'node:http'
import { EventSource } from 'undici'
const server = createServer((request, response) => {
response.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
connection: 'keep-alive'
})
response.write('event: ping\n')
response.write('data: connected\n\n')
const interval = setInterval(() => {
response.write(`data: ${Date.now()}\n\n`)
}, 1000)
request.on('close', () => clearInterval(interval))
})
server.listen(3000, () => {
const eventSource = new EventSource('http://localhost:3000')
// Named event, delivered under its own type.
eventSource.addEventListener('ping', (event) => {
console.log('ping:', event.data)
})
// Unnamed event, delivered as 'message'.
eventSource.onmessage = (event) => {
console.log('message:', event.data)
}
})Emitted when the connection fails or is interrupted. The listener receives an
<Event>. When the failure is recoverable, the EventSource transitions back to
CONNECTING and retries after the reconnection time; when it is not, the
EventSource transitions to CLOSED and does not reconnect.
import { EventSource } from 'undici'
const eventSource = new EventSource('http://localhost:3000')
eventSource.onerror = () => {
if (eventSource.readyState === EventSource.CLOSED) {
console.log('connection closed')
} else {
console.log('reconnecting')
}
}