Beginner LevelREST APIs & Web Services
How do Server-Sent Events (SSE) stream text/event-stream data to clients?
❓ Interview Prompt: Explain Server-Sent Events (SSE), `text/event-stream` content type, persistent HTTP connection, `EventSource` browser API, and unidirectional server pushing.
Server-Sent Events (SSE) is a standardized HTTP streaming technology allowing servers to push real-time updates to web clients over a single long-lived HTTP connection:
SSE vs WebSockets:
•
SSE: Unidirectional (Server $\rightarrow$ Client). Built on standard HTTP ('Content-Type: text/event-stream'). Native browser reconnect logic via 'EventSource'.
•
WebSockets: Bidirectional (Client $\leftrightarrow$ Server). Requires upgrading protocol to TCP WS frame socket.
Code Implementation Example
typescript
// Server-Sent Events Express Handler
app.get('/api/v1/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const timer = setInterval(() => {
res.write('data: \${JSON.stringify({ time: new Date().toISOString() })}\n\n');
}, 1000);
req.on('close', () => clearInterval(timer));
});💡Streaming real-time text/event-stream responses using Server-Sent Events in Express.
🎯 Interview Key Takeaway
Server-Sent Events use text/event-stream over standard HTTP to stream unidirectional real-time updates from server to client.
#SSE#Server-Sent Events#Streaming#Beginner
Back to all REST APIs & Web Services Questions→