Prevent JavaScript Prototype Pollution with Safer Input and Object Design
Prototype pollution is a vulnerability in which attacker-controlled input or library behavior adds or changes properties on a JavaScript object's prototype, causing those values to be inherited by other objects and alter their behavior. Pollution alone does not always complete an attack: impact arises when application code later reads an inherited property in a sensitive place, such as an authorization check, request option, or HTML operation. Prevent it with a combination of input validation, safe object construction, and own-property checks rather than relying on one blocked key.
Why can a prototype affect many objects?
When JavaScript reads a property that an object does not own, it searches the prototype chain. Ordinary objects usually inherit from Object.prototype, so an attacker-controlled property added there may appear on many objects that never received it directly. Changing a built-in or shared prototype this way is called prototype pollution.
The problem often starts when nested user input is copied into an object through a generic merge function or dynamic property assignment. Code that uses obj[key] or follows nested keys recursively may encounter paths such as __proto__, constructor, and prototype. In parsed JSON, "__proto__" is initially an ordinary key. But later assignment by Object.assign(), a for...in loop, or a custom deep-merge routine can trigger special behavior. Successful JSON parsing is therefore not a security check.
A vulnerability usually has two stages:
**Pollution source:** attacker-controlled data from a URL query or fragment, JSON body, message, or configuration reaches a property-copy or merge operation without adequate validation.
**Use site (sink or gadget):** later code trusts the inherited property as if it were an explicitly supplied own property. A missing default or a security-sensitive option can then change behavior.
In browsers, polluted values passed into DOM operations or fetch options may contribute to DOM XSS or altered requests. In Node.js, templates, API configuration, or child-process options may be affected. Remote code execution is not automatic: the input path, polluted object, and vulnerable use site must all line up, and impact depends on the code and its privileges.
Which code patterns deserve review first?
| Pattern | When risk increases | Defensive direction |
|---|---|---|
| Recursive merge, query-string parser, generic merge library | External keys are copied into objects or configuration without an allowlist | Check library versions; validate against a schema and allowed keys |
| obj[key] or nested-path assignment | Keys come from input and may contain __proto__, constructor, or prototype | Validate a fixed set of allowed keys and paths at every nesting level |
| for...in loops and truthiness checks | Inherited properties are treated as input, or missing values are mistaken for safe defaults | Iterate own keys with Object.keys(); use Object.hasOwn() and explicit defaults for security decisions |
| Configuration objects or ad-hoc dictionaries | A normal object is used as a string-key store even though inheritance is unnecessary | Consider Map/Set or Object.create(null) |
These patterns alone do not prove a vulnerability. Trace whether untrusted data actually reaches the code and where it is later consumed. Blocking only __proto__ is not enough to assume safety: constructor.prototype may remain reachable, and parsers and merge libraries differ.
How should input and object use be defended?
Constrain input with a schema. Use a validator such as JSON Schema, Ajv, or Zod to define accepted properties and types, and reject unneeded properties. Do not copy user input wholesale into an options object; construct a new object containing only server-approved fields. Explicitly set safe defaults for authorization values and security options, including when the input omits them.
const allowedConfigKeys = new Set(["theme", "pageSize", "locale"]);
const config = Object.create(null);
for (const [key, value] of Object.entries(input)) {
if (!allowedConfigKeys.has(key)) continue;
config[key] = value;
}This example copies only fixed allowed keys into a dictionary with no inherited prototype. Real code must also validate value types and ranges. An allowlist makes the accepted shape explicit instead of blocking only a few known keys.
Limit dynamic key paths. obj[key] is not inherently vulnerable, but when the key comes from input, validate it against permitted keys and paths. When building nested objects, verify each target at every level. Check the version-specific security guidance for any deep-merge library. Validate the key after decoding and normalization, as that is the value the program will actually use.
Check that sensitive reads use own properties. A check such as if (!user.isAdmin) cannot distinguish an absent property from an inherited one. Confirm that security-sensitive fields are own properties and that the schema guarantees their type and default. For key enumeration, use Object.keys() or Object.entries() instead of for...in.
Choose the right data structure. Map can be a better dictionary for arbitrary string keys. If a normal object is needed but inheritance is not, consider Object.create(null). Such objects do not inherit methods like hasOwnProperty; use Object.hasOwn(obj, key) and confirm that downstream libraries accept the object shape.
Treat runtime flags as defense in depth. Node.js options --disable-proto=delete and --disable-proto=throw reduce one __proto__ entry point, but do not prevent every route through constructor.prototype. Before deployment, test the Node version, startup options, framework and dependency compatibility, and error behavior. Object.freeze(Object.prototype) is shallow and can conflict with polyfills or libraries, so it is not a universal fix to apply without review.
How should a project be reviewed and fixed?
**Find input paths.** Search URL parsers, JSON APIs, message handlers, configuration uploads, and custom merge/parser code. Record third-party libraries and versions that construct nested objects.
**Trace from source to sink.** Identify where input is copied and whether the resulting object reaches authorization checks, templates/DOM, request options, or process options. Finding a source alone does not establish impact.
**Use allowed fields and safer representations.** Apply schema validation, reject extra properties, set explicit defaults, check own properties, and use Map or null-prototype objects where appropriate. Treat special-key filters as a supplementary control and review recursive paths and library behavior separately.
**Add regression tests.** Confirm valid fields still work and unknown fields or risky paths are rejected. Authorization must fail closed when a property is missing, inherited, or the wrong type. Run tests locally or in isolated CI; do not mutate a production process's global prototype.
**Maintain libraries and runtime settings.** Upgrade vulnerable merge/parser libraries to maintainer-fixed versions and update the lock file. Validate Node runtime flags as a separate layer, then check normal requests and error paths.
Success is not merely blocking a few named keys. Tests should show that external input cannot change a shared prototype and that missing or inherited properties do not determine authorization, requests, or rendering. If a fix causes unexpected errors, isolate the changed merge/validation path and check compatibility instead of blindly removing runtime protections.
Is prototype pollution the same vulnerability as XSS?
No. Prototype pollution changes inherited object properties; XSS executes attacker-controlled script in a browser. If a DOM sink uses a polluted property unsafely, pollution may lead to DOM XSS. If the property is safely consumed or no vulnerable gadget exists, pollution may not be exploitable on its own. Validate the input source, whether pollution succeeds, the actual sink, and the resulting privilege impact separately.
References
[MDN — JavaScript prototype pollution: mechanics and defenses](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/Prototype_pollution)
[OWASP — Prototype Pollution Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Prototype_Pollution_Prevention_Cheat_Sheet.html)
[Node.js — Security Best Practices: Prototype Pollution](https://nodejs.org/learn/getting-started/security-best-practices)
[PortSwigger Web Security Academy — Prototype pollution overview](https://portswigger.net/web-security/prototype-pollution)
[PortSwigger — Server-side prototype pollution and detection limits](https://portswigger.net/web-security/prototype-pollution/server-side)