How to Prevent Prototype Pollution in JavaScript
Block prototype pollution from untrusted input: avoid unsafe merges, use null-prototype objects and maps, and validate keys before assignment.
On this page
Introduction
JavaScript objects inherit from a prototype chain that ends at Object.prototype, which every object shares. Prototype pollution is an attack that writes to a prototype through untrusted input, usually via a recursive merge or a key-path assignment that copies a key such as proto. The result is that a property appears on every object in the process, which can change the behavior of code the attacker never touched.
This tutorial explains the sinks, shows how to reject dangerous keys during parsing and merging, recommends null-prototype objects and Map for dictionaries built from input, and tests with payloads that attempt to set proto and constructor.prototype. The examples use plain JavaScript, and the same reasoning applies in Node.js and the browser.
Find the polluting sinks
Pollution needs a write path that follows a key from untrusted input into an object. Recursive merges are the classic sink: a function that iterates the source object’s keys and recurses into nested objects will, given a proto key, recurse into Object.prototype and set properties on it. Any deep-set that walks a dotted path such as ‘a.b.c’ and assigns at the leaf is the same sink if the path comes from input.
The key insight is that JSON.parse is not itself the problem: it creates own properties and does not traverse proto into the prototype when assigning. The problem is the merge or the path-walk that later treats the parsed data as a set of instructions for where to write. Audit code that merges config, applies a patch, or sets a nested value from a request, and treat those as the sinks to harden.
// vulnerable: a deep merge that recurses through __proto__
function unsafeMerge(target, source) {
for (const key of Object.keys(source)) {
if (isObject(source[key])) {
target[key] = target[key] || {};
unsafeMerge(target[key], source[key]); // key="__proto__" walks Object.prototype
} else {
target[key] = source[key];
}
}
return target;
}
Reject dangerous keys at every boundary
Block the keys proto, constructor, and prototype wherever a key or a path segment comes from input. Rejecting them in the parse step stops them before any merge sees them, and rejecting them in the merge is a second line of defense if a value bypassed the parse. A single deny list in a shared utility is easier to audit than a check scattered across call sites.
Apply the check to each path segment, not only the first, because a path such as ‘a.proto.x’ hides the dangerous segment in the middle. If your input encodes nested keys as a delimiter string, split it and check every segment. If it is a nested object, check every key at every depth during traversal, because the recursion is exactly where the pollution happens.
const DANGEROUS = new Set(['__proto__', 'constructor', 'prototype']);
function isSafeKey(key) {
return !DANGEROUS.has(key);
}
function safeMerge(target, source) {
for (const key of Object.keys(source)) {
if (!isSafeKey(key)) continue; // drop the polluting key
const value = source[key];
if (value && typeof value === 'object' && !Array.isArray(value)) {
target[key] = target[key] || Object.create(null);
safeMerge(target[key], value);
} else {
target[key] = value;
}
}
return target;
}
Use null-prototype objects and Map for input
An object created with Object.create(null) has no prototype, so a key like proto is an ordinary own property rather than a link to Object.prototype. Building a dictionary from input on a null-prototype object removes the attack surface for that dictionary entirely. A Map is similar: keys are values, not property names, so a proto key is just a key and cannot reach any prototype.
Choose the structure by use. For a dictionary whose keys come from input and are looked up dynamically, a Map is the cleanest and safest choice. For a plain record you build yourself from validated keys, Object.create(null) avoids the inherited properties that otherwise appear in iteration. Avoid spellings that still touch the prototype, and do not use the proto accessor to set the prototype from input.
// a dictionary built from untrusted keys: use a null-prototype object or a Map
const seen = Object.create(null);
seen['__proto__'] = 'safe'; // own property, Object.prototype untouched
const lookup = new Map();
lookup.set('__proto__', 'safe'); // just a key, no prototype involvement
Freeze and validate as defense in depth
Freezing Object.prototype with Object.freeze(Object.prototype) prevents later writes to it, which blocks the classic pollution at the sink. It is a blunt global change that can break libraries that legitimately modify it, so evaluate it against your dependencies, but where it is safe it removes the target entirely. Treat it as defense in depth, not the only control, because pollution can also target other prototypes in the chain.
Validate input with a schema that rejects unknown fields, so a proto key never reaches your merge in the first place. A strict schema that allows only the expected fields is the strongest boundary control, and the key deny list and null-prototype structures are the backstops for code paths that build objects dynamically.
Test the pollution payloads
Send payloads that attempt to set a property through proto, through constructor.prototype, and through a nested path with the dangerous key in the middle. After each request, assert Object.prototype has no new property, by checking a distinctive property name such as polluted is undefined. Test both the parse-and-merge path and any dotted-path setter, because each is an independent sink.
curl -s -X POST -H 'content-type: application/json' \
-d '{"__proto__":{"polluted":"yes"}}' http://localhost:3000/config
node -e "console.log(({}).polluted)" # expect undefined, not 'yes'
curl -s -X POST -H 'content-type: application/json' \
-d '{"a":{"__proto__":{"polluted":"yes"}}}' http://localhost:3000/config
Common pitfalls
A recursive merge that follows proto, a dotted-path setter that does not check every segment, relying on JSON.parse alone to be safe, building dictionaries as normal objects from untrusted keys, and freezing Object.prototype without also validating input are the recurring mistakes. A key deny list at every boundary, null-prototype objects or Map, schema validation, and targeted freezing address them.
Conclusion
Prototype pollution writes to a shared prototype through input-driven assignment. Reject proto, constructor, and prototype at every path segment, build input dictionaries on null-prototype objects or Maps, validate with a strict schema, and consider freezing Object.prototype as a backstop. Self-check by sending a proto payload and asserting Object.prototype gained no property. Then untrusted input cannot reshape the behavior of the whole process.
Sources: OWASP: Prototype pollution, MDN: Object.prototype and proto, MDN: Map.
FAQ
- What is the actual impact?
- Polluting Object.prototype affects every object in the process, because they all inherit from it. That can flip an authorization check, add an unexpected default, or, combined with a gadget, lead to remote code execution. Even a benign-looking polluted property can break unrelated code.
- Is JSON.parse vulnerable?
- JSON.parse itself does not pollute, because it creates own properties and does not follow __proto__ for assignment in modern engines. The danger is a later merge or a key-path assignment that copies a parsed __proto__ key into a target object recursively.
Report a problem with this articleOpens a pre-filled issue on GitHub.