Skip to content

Commit

Permalink
Add optional id parameter to eventStream SendFunctionArgs (#397)
Browse files Browse the repository at this point in the history
This pull request adds an optional `id`-parameter to the `eventStream`'s
send function.
This id is buffered in the browser and used when reconnecting to an
SSE-endpoint after failure. It's sent as the `Last-Event-ID`-header in
the reconnection request.

See [SSE spec regarding Last-Event-ID
header](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-last-event-id-header)

Co-authored-by: Sergio Xalambrí <[email protected]>
  • Loading branch information
brmlmn and sergiodxa authored Jan 20, 2025
1 parent eec18cf commit 6f4c757
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/server/event-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ interface SendFunctionArgs {
* @default "message"
*/
event?: string;
id?: string;
data: string;
}

Expand Down Expand Up @@ -35,8 +36,9 @@ export function eventStream(
let encoder = new TextEncoder();
let closed = false;

function send({ event = "message", data }: SendFunctionArgs) {
function send({ event = "message", data, id }: SendFunctionArgs) {
if (closed) return; // If already closed, not enqueue anything
if (id) controller.enqueue(encoder.encode(`id: ${id}\n`));
controller.enqueue(encoder.encode(`event: ${event}\n`));

if (closed) return; // If already closed, not enqueue anything
Expand Down

0 comments on commit 6f4c757

Please sign in to comment.