Prev

Server-sent Events

Next

Server-sent Events

  • A one-way communication channel from server to client
  • Suitable for realtime updates.
  • Like one-way WebSockets

Server-sent Events

Vocabulary

Consuming SSE in the browser

The browser has a built-in API, EventSource to consume server-sent events.

  1. Point to a URL that serves an event stream via GET request.
  2. Listen to the onmessage event
eventSource.js

const eventSource = new EventSource("/api/my-event-stream");
eventSource.onmessage = (event) => {
// event.data is always a string. So you may need JSON.parse()
console.log(event.data);
};