JavaScript TutorialDatatypes in JavaScriptEvaluating JavaScriptFunctional JavaScriptJavaScript .postMessage() and MessageEventJavaScript AJAXJavaScript Anti-patternsJavaScript Arithmetic (Math)JavaScript ArraysJavaScript Arrow FunctionsJavaScript Async functions (async/await)JavaScript Async IteratorsJavaScript Automatic Semicolon Insertion - ASIJavaScript Battery Status APIJavaScript Behavioral Design PatternsJavaScript Binary DataJavaScript Bitwise operatorsJavaScript Bitwise Operators - Real World Examples (snippets)JavaScript BOM (Browser Object Model)JavaScript Built-in ConstantsJavaScript CallbacksJavaScript ClassesJavaScript CommentsJavaScript Comparison OperationsJavaScript ConditionsJavaScript ConsoleJavaScript Constructor functionsJavaScript Context (this)JavaScript CookiesJavaScript Creational Design PatternsJavaScript Custom ElementsJavaScript Data attributesJavaScript Data ManipulationJavaScript DateJavaScript Date ComparisonJavaScript DebuggingJavaScript Declarations and AssignmentsJavaScript Destructuring assignmentJavaScript Detecting browserJavaScript EnumerationsJavaScript Error HandlingJavaScript Escape SequencesJavaScript EventsJavaScript execCommand and contenteditableJavaScript FetchJavaScript File API, Blobs and FileReadersJavaScript Fluent APIJavaScript FunctionsJavaScript GeneratorsJavaScript GeolocationJavaScript Global error handling in browsersJavaScript HistoryJavaScript How to make iterator usable inside async callback functionJavaScript IndexedDBJavaScript InheritanceJavaScript Intervals and TimeoutsJavaScript JSONJavaScript Linters - Ensuring code qualityJavaScript LocalizationJavaScript LoopsJavaScript MapJavaScript Memory efficiencyJavaScript Method ChainingJavaScript Modals - PromptsJavaScript Modularization TechniquesJavaScript ModulesJavaScript NamespacingJavaScript Navigator ObjectJavaScript Notifications APIJavaScript ObjectsJavaScript Performance TipsJavaScript PromisesJavaScript Prototypes, objectsJavaScript ProxyJavaScript Regular expressionsJavaScript requestAnimationFrameJavaScript Reserved KeywordsJavaScript Same Origin Policy & Cross-Origin CommunicationJavaScript ScopeJavaScript ScreenJavaScript Security issuesJavaScript Selection APIJavaScript Server-sent eventsJavaScript SetJavaScript Setters and GettersJavaScript Strict modeJavaScript StringsJavaScript SymbolsJavaScript Tail Call OptimizationJavaScript Template Literals

JavaScript Server-sent events

From WikiOD

Syntax[edit | edit source]

  • new EventSource("api/stream");
  • eventSource.onmessage=function(event){}
  • eventSource.onerror=function(event){};
  • eventSource.addEventListener=function(name, callback, options){};
  • eventSource.readyState;
  • eventSource.url;
  • eventSource.close();

Setting up a basic event stream to the server[edit | edit source]

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.


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(;
  // 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.

Closing an event stream[edit | edit source]

An event stream to the server can be closed using the EventSource.close() method

var eventSource = new EventSource("api/my-events");
// do things ...
eventSource.close(); // you will not receive anymore events from this object

The .close() method does nothing is the stream is already closed.

Binding event listeners to EventSource[edit | edit source]

You can bind event listeners to the EventSource object to listen to different events channels using the .addEventListener method.

EventSource.addEventListener(name: String, callback: Function, [options])

name: The name related to the name of the channel the server is emitting events to.

callback: The callback function runs every time an event bound to the channel is emitted, the function provides the event as an argument.

options: Options that characterize the behavior of the event listener.

The following example shows a heartbeat event stream from the server, the server sends events on the heartbeat channel and this routine will always run when an event in accepted.

var eventSource = new EventSource("api/heartbeat");
eventSource.addEventListener("heartbeat", function(event) {
  var status =;
  if (status=='OK') { 
    // do something