Question #5858   Submitted by Answiki on 02/08/2022 at 08:00:37 AM UTC

How to implement server-sent event in Node.js?

Answer   Submitted by Answiki on 02/23/2022 at 10:01:40 AM UTC

To implement SSE in Node.js, the best option is to use Express.js to create the web server. Then, create a route for the event stream :

  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })


Every time the server needs to send an event, use res.write('data: data_to_send');.


The following example is a fully working example in Node.js. The server sends its current time to the client every two seconds.


Server (index.js)

// Express web server framwork
const express = require('express')
const app = express()

// Static files are in the public folder
app.use(express.static('public'))


// Requests on path /see are processed here
app.get('/sse', function(req, res) {
  
  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })

  // Every 2 seconds, send an event with current time
  setInterval(function (res) {
    let date = new Date();    
    res.write('data: The server time is:' + date.toGMTString() + '\n\n');
  }, 2000, res)
})

// Start the server and listen on port 3000
app.listen(3000, () => { console.log ('Server is running on port 3000'); })


Client (/public/index.html)

<h1>SSE demo with PHP</h1>

<ol id="list">
</ol>

<script>
  // Create new event, the server script is sse.php
  var eventSource = new EventSource("/sse");

  // Event when receiving a message from the server
  eventSource.onmessage = function(event) {
    // Append the message to the ordered list
    document.getElementById("list").innerHTML += '<li>'+event.data + "</li>";
  };
</script>

Live example on repl.it.

7 events in history
Answer by Answiki on 02/23/2022 at 10:01:40 AM

To implement SSE in Node.js, the best option is to use Express.js to create the web server. Then, create a route for the event stream :

  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })


Every time the server needs to send an event, use res.write('data: data_to_send');.


The following example is a fully working example in Node.js. The server sends its current time to the client every two seconds.


Server (index.js)

// Express web server framwork
const express = require('express')
const app = express()

// Static files are in the public folder
app.use(express.static('public'))


// Requests on path /see are processed here
app.get('/sse', function(req, res) {
  
  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })

  // Every 2 seconds, send an event with current time
  setInterval(function (res) {
    let date = new Date();    
    res.write('data: The server time is:' + date.toGMTString() + '\n\n');
  }, 2000, res)
})

// Start the server and listen on port 3000
app.listen(3000, () => { console.log ('Server is running on port 3000'); })


Client (/public/index.html)

<h1>SSE demo with PHP</h1>

<ol id="list">
</ol>

<script>
  // Create new event, the server script is sse.php
  var eventSource = new EventSource("/sse");

  // Event when receiving a message from the server
  eventSource.onmessage = function(event) {
    // Append the message to the ordered list
    document.getElementById("list").innerHTML += '<li>'+event.data + "</li>";
  };
</script>

Live example on repl.it.

Answer by Answiki on 02/23/2022 at 09:16:23 AM

To implement SSE in Node.js, the best option is to use Express.js to create the web server. Then, create a route for the event stream :

  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })


Every time the server needs to send an event, use res.write('data: data_to_send');.


The following example is a fully working example in Node.js. The server sends its current time to the client every two seconds.


Server (index.js)

// Express web server framwork
const express = require('express')
const app = express()

// Static files are in the public folder
app.use(express.static('public'))


// Requests on path /see are processed here
app.get('/sse', function(req, res) {
  
  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })

  // Every 2 seconds, send an event with current time
  setInterval(function (res) {
    let date = new Date();    
    res.write('data: The server time is:' + date.toGMTString() + '\n\n');
  }, 2000, res)
})

// Start the server and listen on port 3000
app.listen(3000, () => { console.log ('Server is running on port 3000'); })


Client (/public/index.html)

<h1>SSE demo with PHP</h1>

<ol id="list">
</ol>

<script>
  // Create new event, the server script is sse.php
  var eventSource = new EventSource("/sse");

  // Event when receiving a message from the server
  eventSource.onmessage = function(event) {
    // Append the message to the ordered list
    document.getElementById("list").innerHTML += '<li>'+event.data + "</li>";
  };
</script>

Live example on repl.it.


Note that according to the PHP configuration, the server may buffered data before sending it to the client. You have to check that parameters output_buffering and zlib.output_compression are disabled in file php.ini:

output_buffering = Off
zlib.output_compression = Off




Question by Answiki 02/08/2022 at 08:47:42 AM
How to implement server-sent events in Node.js?
Question by Answiki 02/08/2022 at 08:47:33 AM
How to implement SSE (server-sent events) in Node.js?
Answer by Answiki on 02/08/2022 at 08:13:36 AM

To implement SSE in Node.js, the best option is to use Express.js to create the web server. Then, create a route for the event stream :

  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })


Every time the server needs to send an event, use res.write('data: data_to_send');.


The following example is a fully working example in Node.js. The server sends its current time to the client every two seconds.


Server (index.js)

// Express web server framwork
const express = require('express')
const app = express()

// Static files are in the public folder
app.use(express.static('public'))


// Requests on path /see are processed here
app.get('/sse', function(req, res) {
  
  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })

  // Every 2 seconds, send an event with current time
  setInterval(function (res) {
    let date = new Date();    
    res.write('data: The server time is:' + date.toGMTString() + '\n\n');
  }, 2000, res)
})

// Start the server and listen on port 3000
app.listen(3000, () => { console.log ('Server is running on port 3000'); })


Client (/public/index.html)

<h1>SSE demo with PHP</h1>

<ol id="list">
</ol>

<script>
  // Create new event, the server script is sse.php
  var eventSource = new EventSource("/sse");

  // Event when receiving a message from the server
  eventSource.onmessage = function(event) {
    // Append the message to the ordered list
    document.getElementById("list").innerHTML += '<li>'+event.data + "</li>";
  };
</script>


Live example on repl.it.

Answer by Answiki on 02/08/2022 at 08:13:18 AM

To implement SSE in Node.js, the best option is to use Express.js to create the web server. Then, create a route for the server stream :

  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })


Every time the server needs to send an event, use res.write('data: data_to_send');.


The following example is a fully working example in Node.js. The server sends its current time to the client every two seconds.


Server (index.js)

// Express web server framwork
const express = require('express')
const app = express()

// Static files are in the public folder
app.use(express.static('public'))


// Requests on path /see are processed here
app.get('/sse', function(req, res) {
  
  // Create event(stream header)
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })

  // Every 2 seconds, send an event with current time
  setInterval(function (res) {
    let date = new Date();    
    res.write('data: The server time is:' + date.toGMTString() + '\n\n');
  }, 2000, res)
})

// Start the server and listen on port 3000
app.listen(3000, () => { console.log ('Server is running on port 3000'); })


Client (/public/index.html)

<h1>SSE demo with PHP</h1>

<ol id="list">
</ol>

<script>
  // Create new event, the server script is sse.php
  var eventSource = new EventSource("/sse");

  // Event when receiving a message from the server
  eventSource.onmessage = function(event) {
    // Append the message to the ordered list
    document.getElementById("list").innerHTML += '<li>'+event.data + "</li>";
  };
</script>


Live example on repl.it.

Question by Answiki 02/08/2022 at 08:00:37 AM
How to implement server-sent event in Node.js?
# ID Query URL Count

Icons proudly provided by Friconix.