Improve response transfer efficiency
Reduce transfer size for text-heavy API or web responses.
Express.js · Module
Express’s compression middleware compresses eligible HTTP response bodies using deflate, gzip, or Brotli. Install the compression package and mount compression([options]) with app.use().
Calling compression with an options object creates middleware that evaluates each traversing response for compression. The default filter checks whether the response content type is compressible, while options can adjust filtering, compression level, threshold, and zlib or Brotli behavior.
compression([options])| Name | Type | Description |
|---|---|---|
options | object | Optional configuration object controlling filtering, compression level, threshold, and zlib or Brotli behavior. |
Middleware function that attempts to compress response bodies for requests passing through it.
const express = require('express');
const compression = require('compression');
const app = express();
app.use(compression());
app.get('/', (req, res) => {
res.type('text').send('A response that may be compressed.');
});
app.listen(3000);Installs compression middleware for requests reaching the application, allowing supported response bodies to be compressed according to the client and middleware options.
Reduce transfer size for text-heavy API or web responses.
Apply compression selectively based on request or response properties.
Tune output size and processing cost for application workloads.
compression([options]) returns middleware. That middleware considers response bodies for requests that pass through it, using the supplied options and the client’s supported coding.
Follow-up: How can compression be selectively disabled? Provide a filter function that returns false for requests or responses that should not be compressed.
The default filter uses the compressible module to inspect res.getHeader('Content-Type'). A response is considered for compression when that content type is compressible.
Follow-up: What does a custom filter need to return? It must return true to consider compression or false to skip it.
The middleware supports deflate, gzip, and Brotli through the br coding. Its options can also include zlib options and Brotli options.
Follow-up: What is the trade-off of raising the zlib compression level? It can improve compression while increasing completion time.
express()app.use()compressiblezlibCache-Control