How to receive server-sent event notifications ?
Last Updated :
06 Sep, 2022
This is a one-way communication that is made with the server by making a single persistent connection. Initially, the client makes a connection with the server and waits for the trigger of the event by the server and the server triggers the events on the client by sending some messages to the client.
Now, we will learn to get notified from the server through server-sent events (in short SSE)
We have to use two different perspectives for this task, which are:
- Client Side: To start a connection
- Server Side: To accept the client requests
On the client side, we create an HTML page and with EventSource class we make an asynchronous request to the server.
EventSource class opens a persistent connection with the server and also provides a method to listen to the server events
We need to create an instance of this class, like:
Syntax:
var sse = new EventSource("url");
where,
- sse is the EventSource object
The method used to listen for the server messages is “message“.
Syntax:
sse.onmessage = (event)=>{
...
}
On the Server side, I am using express and nodejs to listen for the client requests, but you can prefer your favorite server-side language.
Syntax:
var express = require("express");
var app = express();
app.get('/events', async function(req, res) {
res.set({
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin':'*'
});
res.flushHeaders();
res.write('hi');
}
app.listen(3000);
In the above code, we are listening at port 3000 and at some URL-PATH
Make sure you make the connection persistent using the header ‘Connection’: ‘keep-alive’ and make the response type as event-stream ‘Content-Type’: ‘text/event-stream’
Browser implements CORS so specify ‘Access-Control-Allow-Origin’:’*’
using res to send notifications to the client.
Example: In the below example we will connect at “http://localhost:3000/events” and print the server message on the console tab. On the server side, we will listen to the “/events” URL using the express GET method.
In the server-side code, we create a function run that registers a listener function, and by using res object we send messages to the EventSource instance.
The server sends the message, which is the value of the counter that counts every one second, iteratively.
HTML
< html >
< body >
< script type = "text/javascript" >
source.addEventListener('message', message => {
console.log('Got', message);
});
</ script >
</ body >
</ html >
|
Output:

OUTPUT
Javascript
'use strict' ;
const express = require( 'express' );
run(). catch (err => console.log(err));
async function run() {
const app = express();
app.get( '/events' , async function (req, res) {
console.log( 'Got /events' );
res.set({
'Cache-Control' : 'no-cache' ,
'Content-Type' : 'text/event-stream' ,
'Connection' : 'keep-alive' ,
'Access-Control-Allow-Origin' : '*'
});
res.flushHeaders();
res.write( 'retry: 1000 \n\n' );
let count = 0;
while ( true ) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log( 'Emit' , ++count);
res.write(`data: ${count}\n\n`);
}
});
await app.listen(3000);
console.log( 'Listening on port 3000' );
}
|
Output: The output represents the emission of the data which is the counter that counts every second

OUTPUT
Similar Reads
How to send push notification using XMPP Server?
In this article, we are going to learn how can we send push notifications using the XMPP server. XMPP stands for extensible Messaging and Presence Protocol and it is a free open-source, cross-platform web server solution stack package. which is easy to install and contains mainly the Apache HTTP Ser
2 min read
What is Server-Sent Events in HTML5 ?
Server-Sent events (SSE) provide a seamless way to automatically update web pages without requiring user interaction. These events allow servers to push real-time data to clients over HTTP connections. The updates for any website come via HTTP connections. This way of communication of updating the
3 min read
React Suite Notification toaster.push Method
React Suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we'll learn about React Suite Notification toast
3 min read
How to Receive JSON Data at Server Side ?
JavaScript Object Notation (JSON) is a data transferring format used to send data to or from the server. It is commonly utilized in API integration due to its benefits and simplicity. In this example, we will utilize XML HttpRequest to deliver data to the server. Frontend: We will use a simple form
2 min read
How to add push notification feature in React JS ?
Adding a push notification feature to your React application can significantly improve user engagement by delivering timely updates, alerts, or messages even when users are not actively using your app. Push notifications are commonly used for sending updates about new content, promotional offers, or
3 min read
React Suite Notification Component
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Notification Component allows the user to display a notification message globally. We can use the following approach in ReactJS to use the React Suite Notificati
2 min read
React Suite Notification With Toaster
React Suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we'll learn about React Suite Notification with
3 min read
React Suite Notification Message Type
React Suite is a front-end library designed for the middle platform and back-end products. React Suite Notification components show notification messages on the screen. The type prop takes a string as value and defines the way the notification will appear, which includes icons of different colors, a
3 min read
React Suite <Notification> Props
React suite is a library of React components that have a sensible UI design and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we'll learn about React Suite Notifica
4 min read
React Suite Notification Props & Hooks
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Notification Component allows the user to display a notification message globally. The notification is also used with a toaster in react-based applications. <
4 min read