Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 50 additions & 3 deletions docs/docs/api/EventSource.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server

## Instantiating EventSource

Undici exports a EventSource class. You can instantiate the EventSource as
Undici exports an EventSource class. You can instantiate the EventSource as
follows:

```mjs
Expand All @@ -19,9 +19,57 @@ eventSource.onmessage = (event) => {
}
```

## Receiving events from a server

EventSource connects to an HTTP endpoint that responds with a `text/event-stream`
content type. The connection stays open and receives events as the server writes
them.

```mjs
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')

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

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

eventSource.onerror = () => {
eventSource.close()
server.close()
}
})
```

The `message` event receives events without an explicit `event:` field. Use
`addEventListener()` to subscribe to named events.

## Using a custom Dispatcher

undici allows you to set your own Dispatcher in the EventSource constructor.
Undici allows you to set your own Dispatcher in the EventSource constructor.

An example which allows you to modify the request headers is:

Expand All @@ -38,7 +86,6 @@ class CustomHeaderAgent extends Agent {
const eventSource = new EventSource('http://localhost:3000', {
dispatcher: new CustomHeaderAgent()
})

```

More information about the EventSource API can be found on
Expand Down
Loading