{"id":17253,"library":"hpp","title":"HPP - HTTP Parameter Pollution Protection","description":"`hpp` is an Express middleware designed to protect web applications from HTTP Parameter Pollution (HPP) attacks. HPP exploits how web frameworks handle multiple parameters with the same name in a single request. This library, currently at version 0.2.3, mitigates this by identifying array parameters in `req.query` and `req.body` (specifically for `application/x-www-form-urlencoded` requests) and assigning only the *last* parameter value to the main `req.query` or `req.body` object. The original, potentially polluted array of values is moved to `req.queryPolluted` or `req.bodyPolluted` for inspection. This ensures that downstream middleware or route handlers only receive a single, consistent value for each parameter, preventing attackers from bypassing input validation or causing unexpected application behavior. It's a low-level security utility, likely in maintenance mode given its stable version and specific scope, and integrates directly into the Express middleware chain.","status":"maintenance","version":"0.2.3","language":"javascript","source_language":"en","source_url":"https://github.com/analog-nico/hpp","tags":["javascript","hpp","http","parameter","pollution","attack","security"],"install":[{"cmd":"npm install hpp","lang":"bash","label":"npm"},{"cmd":"yarn add hpp","lang":"bash","label":"yarn"},{"cmd":"pnpm add hpp","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"HPP is an Express middleware, requiring an Express application to function.","package":"express","optional":false},{"reason":"Required for `hpp` to process `req.body` parameters from POST requests. `hpp` must be applied *after* `body-parser` to function correctly for request bodies.","package":"body-parser","optional":true}],"imports":[{"note":"As of version 0.2.3, `hpp` is primarily a CommonJS module. This `require` syntax is the most reliable way to import it in Node.js environments, even when using modern build tools that transpile to CJS.","wrong":"import hpp from 'hpp';","symbol":"hpp","correct":"const hpp = require('hpp');"},{"note":"When using `hpp` in an ESM context (e.g., `type: \"module\"` in `package.json` or with a bundler), the default import syntax is correct. Ensure your `tsconfig.json` or build configuration correctly handles CommonJS module interop.","wrong":"import { hpp } from 'hpp';","symbol":"hpp","correct":"import hpp from 'hpp';"},{"note":"For TypeScript, `hpp` augments the `express.Request` interface with `queryPolluted` and `bodyPolluted`. You'll typically need to declare module augmentations for full type safety, for example:\n```typescript\ndeclare namespace Express {\n  interface Request {\n    queryPolluted?: { [key: string]: string[] };\n    bodyPolluted?: { [key: string]: string[] };\n  }\n}\n```","symbol":"Request","correct":"import { Request } from 'express';"}],"quickstart":{"code":"import express from 'express';\nimport hpp from 'hpp';\nimport bodyParser from 'body-parser';\n\nconst app = express();\nconst port = 3000;\n\n// Make sure body-parser is used BEFORE hpp to allow hpp to process req.body.\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(bodyParser.json()); // Optional, but common. HPP only checks urlencoded for body.\n\n// Add the HPP middleware. This secures all routes by default.\n// It will move polluted parameters from req.query and req.body to req.queryPolluted and req.bodyPolluted.\napp.use(hpp());\n\n// Example route to demonstrate HPP's effect\napp.get('/search', (req: express.Request, res: express.Response) => {\n  console.log('Original req.query (after HPP):', req.query);\n  console.log('Polluted req.query (if any):', req.queryPolluted);\n  res.send(`Search results for: ${req.query.q || 'N/A'}. Polluted: ${JSON.stringify(req.queryPolluted || {})}`);\n});\n\napp.post('/submit', (req: express.Request, res: express.Response) => {\n    console.log('Original req.body (after HPP):', req.body);\n    console.log('Polluted req.body (if any):', req.bodyPolluted);\n    res.send(`Submitted: ${req.body.item || 'N/A'}. Polluted: ${JSON.stringify(req.bodyPolluted || {})}`);\n});\n\n// Whitelisting example (as per README suggestion)\n// If a specific route requires array parameters, apply HPP with a whitelist option.\napp.get('/multi-select', hpp({ whitelist: ['selectedIds'] }), (req: express.Request, res: express.Response) => {\n    // For /multi-select?selectedIds=1&selectedIds=2\n    // req.query.selectedIds will be ['1', '2'] because of the whitelist here.\n    console.log('Multi-select req.query:', req.query);\n    res.send(`Selected IDs: ${req.query.selectedIds}`);\n});\n\napp.listen(port, () => {\n  console.log(`Server listening at http://localhost:${port}`);\n  console.log(`Test with:`);\n  console.log(`GET http://localhost:${port}/search?q=item1&q=item2`);\n  console.log(`POST http://localhost:${port}/submit -d \"item=val1&item=val2\" -H \"Content-Type: application/x-www-form-urlencoded\"`);\n  console.log(`GET http://localhost:${port}/multi-select?selectedIds=100&selectedIds=200`);\n});","lang":"typescript","description":"Demonstrates how to integrate `hpp` middleware into an Express application to protect against HTTP Parameter Pollution. It shows basic usage, how polluted parameters are moved to `req.queryPolluted` and `req.bodyPolluted`, and an example of whitelisting specific parameters for certain routes."},"warnings":[{"fix":"Ensure `app.use(hpp());` comes *after* `app.use(bodyParser.urlencoded({ extended: true }));`.","message":"The `hpp` middleware must be placed *after* any `body-parser` middleware in your Express application's chain to correctly process `req.body` parameters. If placed before, `req.body` will not be parsed yet, and `hpp` will not be able to mitigate pollution for POST/PUT requests.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Be aware of this limitation and implement separate validation for JSON or multipart bodies if pollution is a concern for those content types. Consider using schema validation libraries for other body types.","message":"`hpp`'s protection for `req.body` parameters is only effective for `application/x-www-form-urlencoded` request bodies. It does not parse or protect `application/json` or `multipart/form-data` bodies. For JSON bodies, ensure your JSON parser and subsequent logic handle potential array inputs appropriately.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Always access parameters from `req.query` and `req.body` after `hpp` has run. Avoid processing data directly from `req.queryPolluted` or `req.bodyPolluted` without explicit, careful handling.","message":"`hpp` does not completely remove polluted parameters; it moves them to `req.queryPolluted` and `req.bodyPolluted`. While `req.query` and `req.body` receive the last safe value, applications should be aware that the original polluted values are still accessible on the `req` object. Sensitive information should not be processed directly from `req.queryPolluted` or `req.bodyPolluted` without strict validation.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure you have `const hpp = require('hpp');` or `import hpp from 'hpp';` at the top of your file and `hpp` is correctly installed via `npm install hpp`.","cause":"The `hpp` module was not correctly imported or required, resulting in `hpp()` being called on an undefined value.","error":"TypeError: app.use() requires a middleware function but got a undefined"},{"fix":"Verify that `app.use(hpp())` is called after `app.use(bodyParser.urlencoded({ extended: true }))`. Also, confirm the client is sending `Content-Type: application/x-www-form-urlencoded` for the body to be processed by `hpp`.","cause":"The `hpp` middleware is placed *before* `body-parser` middleware, or the request body is not `application/x-www-form-urlencoded`.","error":"Parameters in req.body are not being filtered by HPP."}],"ecosystem":"npm","meta_description":null}