When building Node.js applications, especially in the case of larger projects, it becomes paramount to maintain minimal data transfer during client interactions. This practice is instrumental in achieving peak performance on the client side. Consequently, there is a demand for reducing the payload of the responses being sent to users, all the while preserving the integrity of the response content.
A Node.js compression middleware known as Compression the-shelf solution for effectively compressing responses sent from the application to clients. This tool seamlessly addresses the aforementioned need, ensuring that data transmission remains efficient and optimized.
How to implement compression package in to your node application
- install the compression package
npm install compression
- use the compression middleware in your application
Sample code with an Express Application
import express from "express";
import compression from "compression";
const app = express();
const PORT = 7000; // Change this to the port you want to listen on
// Apply compression middleware with custom configuration
app.use(
compression({
level: 6, //
threshold: 0,
filter: (req, res) => {
if (!req.headers['x-no-compression']) {
return compression.filter(req, res);
}
return false; // Don't apply compression if 'x-no-compression' header is present
},
})
);
app.get('/', (req, res) => {
const data = 'This is a post about how to use the compression package'.repeat(10000);
res.send(data);
});
app.listen(PORT, () => {
console.log(Listening on port </span><span class="p">${</span><span class="nx">PORT</span><span class="p">}</span><span class="s2">
);
});
Custom configuration of compression
level
The level of zlib compression to apply to responses. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.
Threshold
The byte threshold for the response body size before compression is considered for the response, defaults to 1kb. This is a number of bytes or any string accepted by the bytes module.
filter
A function to decide if the response should be considered for compression. This function is called as filter(req, res) and is expected to return true to consider the response for compression, or false to not compress the response.
The default filter function uses the compressible module to determine if res.getHeader('Content-Type') is compressible.
Before Compression
After Compression
The size of payload before was 550kb before and after is 181b
Top comments (1)
not working in my code