How to Use Compression Middleware in Express for Faster Responses
Use the
compression middleware in Express by installing it with npm, importing it, and adding app.use(compression()) before your routes. This compresses HTTP responses to make them smaller and faster to send to clients.Syntax
The compression middleware is used by importing it and calling it as a function inside app.use(). This enables gzip compression for all HTTP responses.
const compression = require('compression'): imports the middleware.app.use(compression()): activates compression for all routes.
javascript
const compression = require('compression'); const express = require('express'); const app = express(); app.use(compression()); // Define routes here app.listen(3000);
Example
This example shows a simple Express server using compression middleware to compress responses. When you visit http://localhost:3000, the response will be sent compressed if the client supports it.
javascript
import express from 'express'; import compression from 'compression'; const app = express(); // Enable compression middleware app.use(compression()); app.get('/', (req, res) => { const bigText = 'Hello! '.repeat(1000); // Large response to see compression effect res.send(bigText); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Some common mistakes when using compression middleware include:
- Placing
app.use(compression())after route handlers, so responses are not compressed. - Compressing already compressed files like images or videos, which wastes CPU.
- Not checking client
Accept-Encodingheader, but the middleware handles this automatically.
Always add compression middleware early in the middleware stack.
javascript
const express = require('express'); const compression = require('compression'); const app = express(); // Wrong: compression after routes - no effect app.get('/', (req, res) => { res.send('Hello world'); }); app.use(compression()); // Right: compression before routes // app.use(compression()); // app.get('/', (req, res) => { // res.send('Hello world'); // });
Quick Reference
| Step | Description |
|---|---|
| Install | npm install compression |
| Import | const compression = require('compression') or import compression from 'compression' |
| Use | app.use(compression()) before routes |
| Test | Check response headers for Content-Encoding: gzip |
| Avoid | Compressing already compressed files like images |
Key Takeaways
Add compression middleware early with app.use(compression()) to compress all responses.
Install compression package via npm before using it in your Express app.
Compression reduces response size and speeds up data transfer to clients.
Avoid compressing static files like images; serve them with proper headers instead.
The middleware automatically respects client support for compression.