Practical example of SSE (server sent events) in Node Js

Consider, you have a website for displaying live scores of football match to the end user. You need to send the live scores to the end user as soon as the score changes. You can use server sent events to send the live scores.

It's a hypothetical example, websockets works better for this use case in real world.

Let's see a practical example of SSE in Node Js.

What is SSE?

SSE is a technology to send data from server to client. It's a one way communication from server to client.

const express = require('express')
const app = express()

// Simulated live football data
const footballData = [
  { team: 'Real Madrid', goals: 2, possession: '55%' },
  { team: 'Barcelona', goals: 1, possession: '45%' },
]

app.get('/scores', (req, res) => {
  // text/event-stream is the content type for SSE
  res.setHeader('Content-Type', 'text/event-stream')
  res.setHeader('Cache-Control', 'no-cache')
  // Keep the connection alive so that we can send data to client continuously
  res.setHeader('Connection', 'keep-alive')

  res.write('data: Hello World\n\n')

  // Simulating live streaming of football data every 5 seconds
  const interval = setInterval(() => {
    const randomData =
      footballData[Math.floor(Math.random() * footballData.length)]
    res.write(`data: ${JSON.stringify(randomData)}\n\n`)
  }, 5000)

  // Close the stream after 1 minute
  setTimeout(() => {
    clearInterval(interval)
    console.log('Stream ended\n\n')
    res.end()
  }, 60000)
})

const PORT = 3000
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
})

Practical use cases for SSE

  • Live scores
  • Stock market data
  • Live weather or traffic data
  • Live chat or notifications

Limitations of SSE

  • SSE is a one way communication from server to client. If you need two way communication, you need to use websockets.
  • SSE doesn't work in old browsers. You need to use polyfills to make it work in these browsers.
  • SSE is resource hungry since it opens a new connection for every client. If you have a lot of clients, it will be a problem since you need to scale your server to handle these connections.

Hope you learned the concept of server sent events in node Js using this example 🙌

You can check the followup article on how to consume SSE in React.

Beginners to ProNode Js

Visual Guide to API Design Best Practices

This visual eBook covers essential best practices for designing robust APIs using REST principles.

This book is ideal for beginners and backend developers seeking to enhance their API design skills. However, it is not suited for those seeking an in-depth exploration of API design. This book is a quick read under 40 slides like scrolling through your instagram feed.

Visual Guide to API Design Best Practices