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.

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months