Skip to main content
Go to Latest
Deprecated

(will be removed in 0.209.0) Use ServerSentEventStream from https://deno.land/std/http/server_sent_event_stream.ts instead.

Provides ServerSentEvent and ServerSentEventStreamTarget which provides an interface to send server sent events to a browser using the DOM event model.

The ServerSentEventStreamTarget provides the .asResponse() or .asResponseInit() to provide a body and headers to the client to establish the event connection. This is accomplished by keeping a connection open to the client by not closing the body, which allows events to be sent down the connection and processed by the client browser.

See more about Server-sent events on MDN

Example

import {
ServerSentEvent,
ServerSentEventStreamTarget,
} from "https://deno.land/std@0.208.0/http/unstable_server_sent_event.ts";

Deno.serve({ port: 8000 }, (request) => {
const target = new ServerSentEventStreamTarget();
let counter = 0;

// Sends an event every 2 seconds, incrementing the ID
const id = setInterval(() => {
const evt = new ServerSentEvent(
"message",
{ data: { hello: "world" }, id: counter++ },
);
target.dispatchEvent(evt);
}, 2000);

target.addEventListener("close", () => clearInterval(id));
return target.asResponse();
});
import * as mod from "https://deno.land/std@0.208.0/http/unstable_server_sent_event.ts";