JavaScript Setting up a basic event stream to the server


Example

You can setup your client browser to listen in incoming server events using the EventSource object. You will need to supply the constructor a string of the path to the server' API enpoint the will subscribe the client to the server events.

Example:

var eventSource = new EventSource("api/my-events");

Events have names with which they are categorized and sent, and a listener must be setup to listen to each such event by name. the default event name is message and in order to listen to it you must use the appropriate event listener, .onmessage

evtSource.onmessage = function(event) {
  var data = JSON.parse(event.data);
  // do something with data
}

The above function will run everytime the server will push an event to the client. Data is sent as text/plain, if you send JSON data you may want to parse it.