🚀 Express.js Intermediate

What is compression middleware in Express and when should you use it?

Answer

The compression package adds gzip/deflate/Brotli response compression to Express, reducing bandwidth usage. Install and use: const compression = require('compression'); app.use(compression());. It compresses responses for clients that support it (indicated by the Accept-Encoding header) and sends uncompressed responses otherwise. For JSON APIs, compression can reduce response sizes by 60–80%. It should be near the top of the middleware stack, before response-generating middleware. For high-traffic production apps, offload compression to a reverse proxy like Nginx or a CDN — it is more efficient than compressing at the application layer. Always exclude small responses (under ~1KB) from compression as the overhead outweighs the savings.