How to use gzip in nodejs server
When sending HTTP responses in a Node.js server, you typically need to manually configure compression to ensure that the data is compressed before being sent to the client. The HTTP response object in Node.js does not automatically compress the data; you need to use middleware or manually apply compression techniques.
Using Middleware for Automatic Compression
In a typical Node.js application using Express, you can use the compression
middleware to automatically compress HTTP responses. This middleware uses zlib
under the hood to handle compression and makes it easy to add gzip compression to your responses without manually compressing the data yourself.
Example: Enabling Gzip Compression with Express and Compression Middleware
- Install the
compression
middleware:
npm install compression
- Use the
compression
middleware in your Express application:
const express = require('express');
const compression = require('compression');
const app = express();
// Enable gzip compression
app.use(compression());
app.get('/', (req, res) => {
const data = 'Hello, this is a response from the server!';
res.send(data);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
With this setup, the compression
middleware automatically compresses the response if the client supports gzip compression (as indicated by the Accept-Encoding
header).
Manually Compressing HTTP Responses
If you are not using a framework like Express or if you need more control over the compression process, you can manually compress the response data using the zlib
module.
Example: Manually Compressing an HTTP Response
const http = require('http');
const zlib = require('zlib');
const server = http.createServer((req, res) => {
const data = 'Hello, this is a response from the server!';
// Check if the client supports gzip compression
const acceptEncoding = req.headers['accept-encoding'];
if (acceptEncoding && acceptEncoding.includes('gzip')) {
// Compress the response using gzip
zlib.gzip(data, (err, buffer) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Encoding': 'gzip',
});
res.end(buffer);
}
});
} else {
// Send uncompressed response
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(data);
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the server checks if the client supports gzip compression by inspecting the Accept-Encoding
header. If gzip is supported, the response is compressed using zlib.gzip
before being sent to the client. If gzip is not supported, the server sends the uncompressed response.