DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
mixbo
mixbo

Posted on

What is Server Sent Event

Alt Text

The Server Sent Events specification describes a built-in class EventSource, that keeps connection with the server and allows to receive events from it. similar to WebSocket it’s simpler. In many applications, the power of WebSocket is a little bit too much.

What difference:

  • One-directional: only server sends data

  • Only text

  • Regular HTTP

Getting messages

  1. To start receiving messages, we just need to create new EventSource(url).
  2. The browser will connect to url and keep the connection open, waiting for events.
  3. The server should respond with status 200 and the header Content-Type: text/event-stream
let eventSource = new EventSource("/events/channel");
eventSource.onmessage = function(event) {
  console.log("New message", event.data);
};
Enter fullscreen mode Exit fullscreen mode

Reconnection

Upon creation, new EventSource connects to the server, and if the connection is broken – reconnects. that’s very convenient, as we don’t have to care about it.

Close

let eventSource = new EventSource(...);
eventSource.close();
Enter fullscreen mode Exit fullscreen mode

Event types

By default EventSource object generates three events:

  • message – a message received, available as event.data.
  • open – the connection is open.
  • error – the connection could not be established, e.g. the server returned HTTP 500 status.

Hope it can help you :)

Oldest comments (0)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!