Intermediate LevelExpress JS
Why does the compression middleware break Server-Sent Events (SSE) and streaming endpoints?
❓ Interview Prompt: Explain compression middleware buffering, breaking real-time SSE emissions, and bypassing compression via headers or res.flush().
The 'compression' middleware buffers response chunks in RAM to assemble efficient Gzip compression blocks before sending data to the TCP socket.
The Problem:
This buffering delays real-time Server-Sent Events (SSE) emissions, holding real-time ticks in RAM instead of streaming them immediately!
Fixes:
1
Bypass compression for SSE by setting 'req.headers["x-no-compression"] = "true"' in SSE routes.
2
Call 'res.flush()' after every SSE 'res.write()' to flush the compression buffer instantly.
Code Implementation Example
javascript
import express from 'express';
import compression from 'compression';
const app = express();
app.use(compression());
app.get('/events', (req, res) => {
// Bypass Gzip compression buffering for real-time SSE!
req.headers['x-no-compression'] = 'true';
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('data: {"tick": 1}\n\n');
});💡Bypassing Gzip compression buffering on Server-Sent Events streams.
🎯 Interview Key Takeaway
Bypass response compression on SSE streams using x-no-compression headers to prevent real-time data buffering.
#compression#SSE#Streaming#Intermediate
Back to all Express JS Questions→