How to Use hpp Middleware to Prevent Parameter Pollution in Express
Use the
hpp middleware in Express by installing it with npm and adding app.use(hpp()) to your app. This middleware cleans up duplicate query parameters to prevent HTTP parameter pollution attacks by only keeping the last value for each parameter.Syntax
The hpp middleware is used by importing it and then applying it to your Express app with app.use(hpp()). You can optionally pass an object to whitelist parameters that can have multiple values.
hpp(): Basic usage to remove duplicate parameters.hpp({ whitelist: ['param1', 'param2'] }): Allows specified parameters to keep multiple values.
javascript
import express from 'express'; import hpp from 'hpp'; const app = express(); // Basic usage app.use(hpp()); // Usage with whitelist // app.use(hpp({ whitelist: ['tags'] }));
Example
This example shows how hpp removes duplicate query parameters. When a request has repeated parameters, only the last one is kept.
javascript
import express from 'express'; import hpp from 'hpp'; const app = express(); app.use(hpp()); app.get('/search', (req, res) => { res.json(req.query); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
// Request example:
// GET /search?color=red&color=blue&size=large
// Response:
// { "color": "blue", "size": "large" }
Common Pitfalls
One common mistake is not using hpp middleware early enough in the middleware chain, which can let polluted parameters pass through. Another is forgetting to whitelist parameters that legitimately accept multiple values, causing unexpected data loss.
Also, hpp only cleans query and body parameters, so headers or other inputs need separate handling.
javascript
import express from 'express'; import hpp from 'hpp'; const app = express(); // Wrong: Using hpp after route handlers app.get('/test', (req, res) => { res.json(req.query); }); app.use(hpp()); // Too late, pollution not prevented // Right: Use hpp before routes // app.use(hpp()); // app.get('/test', (req, res) => { // res.json(req.query); // });
Quick Reference
- Install:
npm install hpp - Import:
import hpp from 'hpp' - Use:
app.use(hpp())before routes - Whitelist: Pass
{ whitelist: ['param'] }to allow multiple values - Purpose: Prevent HTTP Parameter Pollution attacks by cleaning duplicate parameters
Key Takeaways
Use the hpp middleware early in your Express app to prevent parameter pollution.
By default, hpp keeps only the last value of duplicate parameters to avoid confusion.
Whitelist parameters that should accept multiple values to avoid data loss.
hpp protects query and body parameters but not headers or other inputs.
Installing and using hpp is simple and improves your app's security against parameter pollution.