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.
Previous
How do you implement file uploads in Express.js?
Next
What is the difference between PUT and PATCH in REST?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?