Search code examples
node.jsgoogle-chrome-devtoolsserver-sent-events

Server sent events showing blank in chrome devtools for simple express SSE


Here is the simple code sample to send SSE using express program (which is working fine). Only trouble is the devtools eventStream section is blank. Empty event stream

const express = require('express')

const app = express()
app.use(express.static('public'))

app.get('/countdown', function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    "Access-Control-Allow-Origin": "*"
  })
  countdown(res, 10)
})

function countdown(res, count) {
  res.write(JSON.stringify({ count: count}))
  if (count)
    setTimeout(() => countdown(res, count-1), 1000)
  else
    res.end()
}

app.listen(3000, () => console.log('SSE app listening on port 3000!'))

Solution

  • You must format the event like that :

    const express = require('express');
    
    const app = express();
    app.use(express.static('public'));
    
    app.get('/countdown', function(req, res) {
      res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        'Access-Control-Allow-Origin': '*'
      });
      countdown(res, 1, 10);
    });
    
    function countdown(res, id, count) {
      res.write(`id: ${id}\n`);
      res.write('event: count\n');
      res.write(`data: ${JSON.stringify({ count: count })}\n\n`);
      if (count) setTimeout(() => countdown(res, id + 1, count - 1), 1000);
      else res.end();
    }
    
    app.listen(3000, () => console.log('SSE app listening on port 3000!'));
    

    And in your front page use EventSource :

    <script>
      var source = new EventSource('http://localhost:3000/countdown');
      source.onmessage = function(event) {
        console.log(event);
      };
    </script>
    

    enter image description here