Node.js compression middleware
The compression package is a Node.js middleware that automatically compresses HTTP response bodies before sending them to clients. With over 35 million weekly downloads, it's one of the most widely adopted performance optimization tools in the Node.js ecosystem. The middleware intercepts outgoing responses and applies compression algorithms (gzip, deflate, or brotli) when clients indicate support via the Accept-Encoding header.
Compression works by analyzing the Content-Type of responses and applying appropriate compression for text-based content like HTML, CSS, JavaScript, and JSON. The middleware is intelligent enough to skip compression for responses that are too small (where compression overhead exceeds benefits), already compressed content, or responses with Cache-Control: no-transform directives. This automatic handling makes it a plug-and-play solution for most Express and Connect-based applications.
The package is particularly valuable for applications serving large amounts of text-based content. In production environments, compression can reduce response sizes by 60-85% for typical web assets, with some cases achieving up to 90% reduction. This translates directly to faster page load times, reduced bandwidth costs, and improved user experience, especially for users on slower connections or mobile networks.
While compression is highly effective for on-demand compression of dynamic content, teams serving primarily static assets may benefit more from pre-compression strategies or offloading compression to reverse proxies like nginx. The CPU overhead of real-time compression is minimal for most applications, but high-traffic services with tight latency budgets should benchmark the impact.
const express = require('express');
const compression = require('compression');
const app = express();
app.use(compression({
level: 6,
threshold: 1024,
filter: (req, res) => {
if (req.headers['x-no-compression']) {
return false;
}
return compression.filter(req, res);
}
}));
app.get('/api/users', (req, res) => {
const users = Array.from({ length: 1000 }, (_, i) => ({
id: i,
name: `User ${i}`,
email: `user${i}@example.com`,
bio: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'.repeat(5)
}));
res.json(users);
});
app.get('/health', (req, res) => {
res.set('Cache-Control', 'no-transform');
res.send('OK');
});
app.listen(3000, () => {
console.log('Server with compression running on port 3000');
});API response compression: REST APIs returning JSON or XML payloads benefit significantly from compression, especially when returning large datasets, search results, or paginated lists. A 200KB JSON response can be compressed to 30-40KB, reducing mobile data usage and improving response times.
Server-side rendered applications: Applications using template engines like EJS, Pug, or Handlebars that generate HTML on each request see substantial benefits. The generated HTML typically compresses well due to repetitive structure and whitespace.
Express applications with mixed content: Web applications serving both dynamic and static content can use compression as a catch-all solution before implementing more sophisticated caching strategies. It provides immediate performance improvements with minimal code changes.
Microservices communication: Internal service-to-service communication over HTTP can benefit from compression when transferring large payloads, reducing network bandwidth in containerized environments where services communicate frequently.
Legacy application optimization: Adding compression to older Express applications is a quick win that requires minimal code changes and no modifications to existing route handlers, making it ideal for incremental performance improvements.
npm install compressionpnpm add compressionbun add compression