Skip to content

API reference

Extends from EventEmitter.

A Session represents an open connection between the server and the client.

It emits the connected event after it has connected and sent the response head to the client.
It emits the disconnected event after the connection has been closed.

When using the Fetch API, the session is considered connected only once the ReadableStream contained in the body of the Response returned by getResponse has began being consumed.

When using the Node HTTP APIs, the session will send the response status code, headers and other preamble data ahead of time, allowing the session to connect and start pushing events immediately. As such, keep in mind that attempting to write additional headers after the session has been created will result in an error being thrown.

new Session<State = DefaultSessionState>(req: IncomingMessage | Http2ServerRequest | Request, res?: ServerResponse | Http2ServerResponse | Response | SessionOptions[, options: SessionOptions])

Section titled “new Session<State = DefaultSessionState>(req: IncomingMessage | Http2ServerRequest | Request, res?: ServerResponse | Http2ServerResponse | Response | SessionOptions[, options: SessionOptions])”

Overloads:

new Session(IncomingMessage, ServerResponse, SessionOptions?)
new Session(Http2ServerRequest, Http2ServerResponse, SessionOptions?)
new Session(Request, Response, SessionOptions?)
new Session(Request, SessionOptions?)

req is an instance of IncomingMessage, Http2ServerRequest or Request.

res is an instance of ServerResponse, Http2ServerResponse or Response, respectively.

options is a SessionOptions object with the following properties:

PropertyTypeDefaultDescription
serializerfunctionJSON.stringifySerialize data to a string that can be written over the wire.

Note that only values written with push are serialized, as everything else is assumed to already be a string.
sanitizerfunctionSanitize values so as to not prematurely dispatch events when writing fields whose text inadvertently contains newlines.

By default, CR, LF and CRLF characters are replaced with a single LF character (\n) and then any trailing LF characters are stripped.
trustClientEventIdbooleantrueWhether to trust or ignore the last event ID given by the client in the Last-Event-ID request header.

When set to false, the lastId property will always be initialized to an empty string.
retrynumber | null2000Time in milliseconds for the client to wait before attempting to reconnect if the connection is closed.

Give as null to avoid sending an explicit reconnection time and allow the client browser to decide itself.
keepAlivenumber | null10000Time in milliseconds interval for the session to send a comment to keep the connection alive.

Give as null to disable the keep-alive mechanism.
statusCodenumber200Status code to be sent to the client.

Event stream requests can be redirected using HTTP 301 and 307 status codes. Make sure to set Location header when using these status codes (301/307) using the headers property.

A client can be asked to stop reconnecting by send a 204 status code.
headersobject{}Additional headers to be sent along with the response.
stateStateDefaultSessionStateInitial custom state for the session.

Accessed via the state property.

When using TypeScript, providing the initial state structure allows the type of the state property to be automatically inferred.

The last event ID sent to the client.

This is initialized to the last event ID given by the user (in the Last-Event-ID header) and otherwise is equal to the last ID given to or generated by the push method.

For security reasons, keep in mind that the client can provide any initial ID here. Use the trustClientEventId constructor option to ignore the client-given initial ID.

Indicates whether the session and underlying connection is open or not.

Custom state for this session.

Use this object to safely store information related to the session and user.

You may set an initial value for this property using the state property in the constructor options object, allowing its type to be automatically inferred.

Use module augmentation and declaration merging to safely add new properties to the DefaultSessionState interface.

Get a Request object representing the request of the underlying connection this session manages.

When using the Fetch API, this will be the original Request object passed to the session constructor.

When using the Node HTTP APIs, this will be a new Request object with status code and headers copied from the original request.
When the originally given request or response is closed, the abort signal attached to this Request will be triggered.

Get a Response object representing the response of the underlying connection this session manages.

When using the Fetch API, this will be a new Response object with status code and headers copied from the original response if given.
Its body will be a ReadableStream that should begin being consumed for the session to consider itself connected.

When using the Node HTTP APIs, this will be a new Response object with status code and headers copied from the original response.
Its body will be null, as data is instead written to the stream of the originally given response object.

Session#push: (data: unknown[, eventName: string[, eventId: string]]) => this

Section titled “Session#push: (data: unknown[, eventName: string[, eventId: string]]) => this”

Push an event to the client.

If no event name is given, the event name is set to "message".

If no event ID is given, the event ID (and thus the lastId property) is set to a randomly generated UUIDv4.

If the session has disconnected, an SseError will be thrown.

Emits the push event with the given data, event name and event ID in that order.

Session#stream: (stream: stream.Readable | ReadableStream[, options: object]) => Promise<boolean>

Section titled “Session#stream: (stream: stream.Readable | ReadableStream[, options: object]) => Promise<boolean>”

Pipe readable stream data to the client.

Each data emission by the stream pushes a new event to the client.

This uses the push method under the hood.

Returns a promise that resolves with true once the stream has been fully consumed and all data is sent to the client.

options.TypeDefaultDescription
eventNamestring"stream"Event name to use when dispatching a data event from the stream to the client.

Session#iterate: (iterable: Iterable | AsyncIterable[, options: object]) => Promise<void>

Section titled “Session#iterate: (iterable: Iterable | AsyncIterable[, options: object]) => Promise<void>”

Iterate over an iterable and send yielded values to the client.

Each yield pushes a new event to the client.

This uses the push method under the hood.

options.TypeDefaultDescription
eventNamestring"iteration"Event name to use when dispatching a data event from the yielded value to the client.

Session#batch: (batcher: EventBuffer | ((buffer: EventBuffer) => void | Promise<void>)) => Promise<void>

Section titled “Session#batch: (batcher: EventBuffer | ((buffer: EventBuffer) => void | Promise<void>)) => Promise<void>”

Batch and send multiple events at once.

If given an EventBuffer instance, its contents will be sent to the client.

If given a callback, it will be passed an instance of EventBuffer which uses the same serializer and sanitizer as the session.
Once its execution completes - or once it resolves if it returns a promise - the contents of the passed EventBuffer will be sent to the client.

Returns a promise that resolves once all data from the event buffer has been successfully sent to the client.

createSession: <State>(...args: ConstructorParameters<typeof Session>) => Promise<Session<State>>

Section titled “createSession: <State>(...args: ConstructorParameters<typeof Session>) => Promise<Session<State>>”

Overloads:

createSession(IncomingMessage, ServerResponse, SessionOptions?): Promise<Session>
createSession(Http2ServerRequest, Http2ServerResponse, SessionOptions?): Promise<Session>
createSession(Request, Response, SessionOptions?): Promise<Session>
createSession(Request, SessionOptions?): Promise<Session>

Create a new Session.

Takes the same arguments as the Session class constructor.

When using the Fetch API, resolves immediately with a session instance before it has connected.
You can listen for the connected event on the session to know when it has connected, or otherwise use the shorthand createResponse function that does so for you instead.

When using the Node HTTP APIs, waits for the session to connect before resolving with its instance.

createResponse: <State>(...args: ConstructorParameters<typeof Session>, callback: (session: Session<State>) => void) => Response

Section titled “createResponse: <State>(...args: ConstructorParameters<typeof Session>, callback: (session: Session<State>) => void) => Response”

Overloads:

createResponse(Request, CreateResponseCallback): Response
createResponse(Request, SessionOptions, CreateResponseCallback): Response
createResponse(Request, Response, CreateResponseCallback): Response
createResponse(Request, Response, SessionOptions, CreateResponseCallback): Response

Create a new session using the Fetch API and return its corresponding Response object.

Takes the same arguments as the Session class constructor.

The last argument should be a callback function CreateResponseCallback that will be invoked with the session instance once it has connected.

The following two code snippets are equivalent:

const session = await createSession(request)
session.addListener("connected", () => {
session.push("Hello world!")
})
return session.getResponse()
return createResponse(request, (session) => {
session.push("Hello world!")
})

Extends from EventEmitter.

A Channel is used to broadcast events to many sessions at once.

You may use the second generic argument SessionState to enforce that only sessions with the same state type may be registered with this channel.

new Channel<State = DefaultChannelState, SessionState = DefaultSessionState>([options: ChannelOptions])

Section titled “new Channel<State = DefaultChannelState, SessionState = DefaultSessionState>([options: ChannelOptions])”

options is a ChannelOptions object with the following properties:

PropertyTypeDefaultDescription
stateStateDefaultChannelStateInitial custom state for the channel.

Accessed via the state property.

When using TypeScript, providing the initial state structure allows the type of the state property to be automatically inferred.

Custom state for this channel.

Use this object to safely store information related to the channel.

You may set an initial value for this property using the state property in the constructor options object, allowing its type to be automatically inferred.

Use module augmentation and declaration merging to safely add new properties to the DefaultChannelState interface.

Channel#activeSessions: ReadonlyArray<Session>

Section titled “Channel#activeSessions: ReadonlyArray<Session>”

List of the currently active sessions subscribed to this channel.

You should not mutate the contents of this array.

Number of sessions subscribed to this channel.

Equivalent to channel.activeSessions.length, though slightly faster to access.

Channel#register: (session: Session) => this

Section titled “Channel#register: (session: Session) => this”

Register a session so that it can start receiving events from this channel.

Note that a session must be connected before it can be registered to a channel.

Fires the session-registered event with the registered session as its first argument.

If the session was already registered to begin with this method does nothing.

Channel#deregister: (session: Session) => this

Section titled “Channel#deregister: (session: Session) => this”

Deregister a session so that it no longer receives events from this channel.

Note that sessions are automatically deregistered when they are disconnected.

Fires the session-deregistered event with the session as its first argument.

If the session was disconnected the channel will also fire the session-disconnected event with the disconnected session as its first argument beforehand.

If the session was not registered to begin with this method does nothing.

Channel#broadcast: (data: unknown[, eventName: string[, options: object]]) => this

Section titled “Channel#broadcast: (data: unknown[, eventName: string[, options: object]]) => this”

Broadcasts an event with the given data and name to every active session registered with this channel.

Under the hood this calls the push method on every active session.

If no event name is given, the event name is set to "message".

Emits the broadcast event with the given data, event name and event ID in that order.

Note that the broadcasted event will have the same ID across all receiving sessions instead of generating a unique ID for each.

options.TypeDefaultDescription
eventIdstringUnique ID for the event being broadcast.

If no event ID is given, the event ID is set to a randomly generated UUIDv4.
filter(session: Session) => booleanFilter sessions that should receive the event.

Called with each session and should return true to allow the event to be sent and otherwise return false to prevent the session from receiving the event.

createChannel: <State, SessionState>(...args: ConstructorParameters<typeof Channel>) => Channel<State>

Section titled “createChannel: <State, SessionState>(...args: ConstructorParameters<typeof Channel>) => Channel<State>”

Creates and returns an instance of a Channel.

Takes the same arguments as the Channel class constructor.

An EventBuffer allows you to write raw spec-compliant SSE fields into a text buffer that can be sent directly over the wire.

new EventBuffer([options: EventBufferOptions])

Section titled “new EventBuffer([options: EventBufferOptions])”

options is an EventBufferOptions object with the following properties:

PropertyTypeDefaultDescription
serializerfunctionJSON.stringifySerialize data to a string that can be written over the wire.

Note that only values written with data (and implicitly push) are serialized, as everything else is assumed to already be a string.
sanitizerfunctionSanitize values so as to not prematurely dispatch events when writing fields whose text inadvertently contains newlines.

By default, CR, LF and CRLF characters are replaced with a single LF character (\n) and then any trailing LF characters are stripped.

Write an event name field (also referred to as the event “type” in the specification).

Write arbitrary data into a data field.

Data is serialized to a string using the given serializer function option or JSON stringification by default.

Write an event ID field.

Defaults to an empty string if no argument is given.

Write a retry field that suggests a reconnection time with the given milliseconds.

EventBuffer#comment: ([text: string]) => this

Section titled “EventBuffer#comment: ([text: string]) => this”

Write a comment (an ignored field).

This will not fire an event but is often used to keep the connection alive.

Indicate that the event has finished being created by writing an additional newline character.

EventBuffer#push: (data: unknown[, eventName: string[, eventId: string]]) => this

Section titled “EventBuffer#push: (data: unknown[, eventName: string[, eventId: string]]) => this”

Create, write and dispatch an event with the given data all at once.

This is equivalent to calling the methods event, id, data and dispatch in that order.

If no event name is given, the event name is set to "message".

If no event ID is given, the event ID is set to a randomly generated UUIDv4.

EventBuffer#stream: (stream: stream.Readable | ReadableStream[, options: object]) => Promise<boolean>

Section titled “EventBuffer#stream: (stream: stream.Readable | ReadableStream[, options: object]) => Promise<boolean>”

Pipe readable stream data as a series of events into the buffer.

Each data emission by the stream pushes a new event.

This uses the push method under the hood.

Returns a promise that resolves with true once the stream has been fully consumed.

options.TypeDefaultDescription
eventNamestring"stream"Event name to use for each event created.

EventBuffer#iterate: (iterable: Iterable | AsyncIterable[, options: object]) => Promise<void>

Section titled “EventBuffer#iterate: (iterable: Iterable | AsyncIterable[, options: object]) => Promise<void>”

Iterate over an iterable and write yielded values as events into the buffer.

This uses the push method under the hood.

options.TypeDefaultDescription
eventNamestring"iteration"Event name to use for each event created.

Clear the contents of the buffer.

Get a copy of the buffer contents.

createEventBuffer: (...args: ConstructorParameters<typeof EventBuffer>) => EventBuffer

Section titled “createEventBuffer: (...args: ConstructorParameters<typeof EventBuffer>) => EventBuffer”

Creates and returns an instance of an EventBuffer.

Takes the same arguments as the EventBuffer class constructor.

Extends from Error.

Represents an SSE-related error thrown from within Better SSE.