Skip to main content
Deno 2 is finally here 🎉️
Learn more
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
import * as mod from "https://deno.land/std@0.205.0/http/unstable_server_sent_event.ts";

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.205.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();
});

Classes

An event which contains information which will be sent to the remote connection and be made available in an EventSource as an event. A server creates new events and dispatches them on the target which will then be sent to a client.

An implementation of ServerSentEventTarget that provides a readable stream as a body of a response to establish a connection to a client.