How to send compressed response in Express app
Using the compression middleware in an Express application can significantly reduce the size of the response body and increase the speed of web applications. This middleware compresses the HTTP response sent back to the client, using gzip compression by default.
Here’s how to set it up in an Express application:
Step-by-Step Guide
-
Install
compressionPackage:First, you need to install the
compressionpackage:npm install compression -
Set Up Express Application with
compression:Here’s an example of how to integrate
compressioninto an Express application:const express = require('express'); const compression = require('compression'); const app = express(); // Use compression middleware app.use(compression()); // Example route app.get('/', (req, res) => { const largeData = 'a'.repeat(1000); // Simulating large response data res.send(`Compressed response data: ${largeData}`); }); // Another route app.get('/hello', (req, res) => { res.send('Hello, world!'); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); -
Explanation:
- Install
compressionPackage:npm install compressioninstalls the compression middleware. - Use Compression Middleware:
app.use(compression());integrates the compression middleware into your Express application. This will compress all responses unless the client indicates that it does not support compression. - Example Routes: Two routes (
/and/hello) are defined to demonstrate the effect of the compression middleware. The root route (/) sends a large response to highlight the benefits of compression.
- Install
-
Testing:
- Run Your Server: Start your server using
node app.js. - Access Routes: Open a browser and navigate to
http://localhost:3000/andhttp://localhost:3000/hello. - Inspect Headers: Use browser developer tools or tools like
curlto inspect the response headers. You should see theContent-Encoding: gzipheader indicating that the response is compressed.
- Run Your Server: Start your server using
Testing with curl
You can use curl to see the difference in response size with and without compression.
Without Compression (you would need to comment out the compression middleware line in your code):
curl -I http://localhost:3000/
With Compression:
curl -I --compressed http://localhost:3000/
You should see the Content-Encoding: gzip header in the response when the compression middleware is active, indicating that the response is compressed.