QA
Intermediate LevelExpress JS

How do you implement unidirectional real-time data streaming using Server-Sent Events (SSE)?

❓ Interview Prompt: Explain Server-Sent Events (SSE), text/event-stream headers, streaming real-time ticks over persistent HTTP connections, and closing sockets.

Server-Sent Events (SSE) provide simple, unidirectional real-time data streaming from server to browser over standard HTTP without WebSocket protocols.

Express Implementation:

1
Set headers: 'Content-Type: text/event-stream', 'Cache-Control: no-cache', 'Connection: keep-alive'.
2
Write event streams formatted as **'data: {JSON}

'**.

3
Listen for client disconnection ('req.on("close")') to clear timers and close sockets cleanly.

Code Implementation Example

javascript
import express from 'express';
const app = express();

app.get('/api/live-ticks', (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  const interval = setInterval(() => {
    res.write(`data: ${JSON.stringify({ timestamp: Date.now() })}\n\n`);
  }, 1000);

  req.on('close', () => {
    clearInterval(interval);
    res.end();
  });
});
💡Streaming real-time server events to clients using Server-Sent Events (SSE).
🎯 Interview Key Takeaway

Use Server-Sent Events (SSE) with text/event-stream headers for simple unidirectional real-time data streaming.

#SSE#Streaming#Real-Time#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?