Languages
[Edit]
EN

Node.js - server-sent events example using Express.js

3 points
Created by:
Creg
9600

In this article, we would like to show how to use server-sent events with Express.js under Node.js.

In the example project we used HTTP/2 protocol for better performance (spdy package).

 

Warning from MDN:

When not used over HTTP/2, SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com. (from Stackoverflow). When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100).

Source: https://developer.mozilla.org/en-US/docs/Web/API/EventSource

 

Project structure

Edit
Server-sent events project created using Express.js.
Server-sent events project created using Express.js.

 

Project files

Edit

To generate cert.pem and key.pem files use the following command:

Hint: to know how to generate certificate files under Windows read this article.

 

package.json file:

 

index.html file:

Note: event source can be closed by source.close() method call.

 

server.js file:

 

Packages installation

Edit

To all dependencies use the following command:

 

Server running

Edit

To run server use the following command:

Then, to see the final effect, open the link in the web browser: https://localhost:8443

 

Example preview:

Express.js server-sent events application tested under web browser.
Express.js server-sent events application tested under web browser.

 

See also

Edit
  1. OpenSSL - generate localhost *.pem certificate under Windows

References

Edit
  1. Server-sent events - MDN Docs
  2. EventSource - MDN Docs
  3. spdy package - NPM Repository
  4. express package - NPM Repository

Alternative titles

  1. Express.js - server-sent events example
  2. Express.js - server events example
  3. Node.js - server events example using Express.js
  4. Node.js - SSE example using Express.js
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join