Home  Express   How to send ...

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

  1. Install compression Package:

    First, you need to install the compression package:

    npm install compression
    
  2. Set Up Express Application with compression:

    Here’s an example of how to integrate compression into 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}`);
    });
    
  3. Explanation:

    • Install compression Package: npm install compression installs 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.
  4. Testing:

    • Run Your Server: Start your server using node app.js.
    • Access Routes: Open a browser and navigate to http://localhost:3000/ and http://localhost:3000/hello.
    • Inspect Headers: Use browser developer tools or tools like curl to inspect the response headers. You should see the Content-Encoding: gzip header indicating that the response is compressed.

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.

Published on: Jun 29, 2024, 04:33 PM  
 

Comments

Add your comment