JSON.parse doesn't pollute your prototype — the copy does

I went looking for a prototype pollution bug in a request handler and spent an hour staring at JSON.parse, convinced it was the line that polluted my object’s prototype. It was not. It never is.
The payload was the classic one, the shape every security write-up uses as its example:
{"name": "ehsan", "__proto__": {"isAdmin": true}}The reasoning felt airtight. That is where an untrusted string becomes an object, so that is where the bad thing must happen.
Except it does not. I ran it and checked:
const parsed = JSON.parse('{"name":"ehsan","__proto__":{"isAdmin":true}}')
console.log(parsed.isAdmin) // undefined
console.log(({}).isAdmin) // undefined
console.log(Object.keys(parsed)) // [ 'name', '__proto__' ]Nothing is polluted. Not this object, not any other object. JSON.parse handed me a completely ordinary object that happens to have a key with an unfortunate name sitting on it, like a letter addressed to someone dangerous that nobody has opened yet.
The explosion happens on the next line, when something copies that object. And here is the part that surprised me: it depends entirely on how you copy it. Some ways are perfectly safe. Some quietly break one object. One breaks your whole process.
A sixty-second refresher on prototypes
Skip this if you already know it.
Every plain JavaScript object has a hidden parent called its prototype. When you ask an object for a property it does not have, JavaScript asks the parent instead.
const user = { name: "ehsan" }
user.toString // user has no toString... but this is a function anywayThat works because user does not have toString, so JavaScript walks up to the shared parent — Object.prototype — and finds it there. Almost every object in your program shares that same parent.
The name __proto__ is a magic doorway to that parent. Writing to it does not create a normal property. It changes who the object’s parent is.
So “prototype pollution” means an attacker got a value written into a parent object. If they reach the shared one, every object in your program inherits their value. A permission check like if (user.isAdmin) starts returning true for users who never had that field.
The test
I wrote one payload and copied it eight different ways, then checked three things each time: does the copy keep __proto__ as a normal key, does the copy claim isAdmin, and what does the copy look like when you serialize it.
const RAW = '{"name":"ehsan","__proto__":{"isAdmin":true}}'
const fresh = () => JSON.parse(RAW)Here is what came back on Node v22.16.0.
| How you copy it | Keeps __proto__ as data | Copy claims isAdmin | JSON.stringify of the copy |
|---|---|---|---|
{...o} (spread) | yes | no | {"name":"ehsan","__proto__":...} |
structuredClone(o) | yes | no | {"name":"ehsan","__proto__":...} |
JSON.parse(JSON.stringify(o)) | yes | no | {"name":"ehsan","__proto__":...} |
Object.defineProperty in a loop | yes | no | {"name":"ehsan","__proto__":...} |
Object.assign({}, o) | no | yes | {"name":"ehsan"} |
for (const k of Object.keys(o)) t[k] = o[k] | no | yes | {"name":"ehsan"} |
for (const [k,v] of Object.entries(o)) t[k] = v | no | yes | {"name":"ehsan"} |
for (const k in o) t[k] = o[k] | no | yes | {"name":"ehsan"} |
Two groups, and the split is not where I expected it to be.
The rule: assignment is the dangerous verb
Look at what the bottom four have in common. Every one of them ends up running target[key] = value where key is the string "__proto__". That is the magic doorway. It reparents target instead of storing anything.
Object.assign belongs to this group, which is the part that catches people. It looks like a copy helper, but internally it assigns, so it hits the doorway exactly like a hand-written loop does. This is not obscure trivia — MDN says it outright: it uses [[Set]] on the target and so “assigns properties, versus copying or defining new properties.” I had read that sentence before without once connecting it to __proto__.
The top four never assign. Spread, structuredClone, a JSON round-trip and Object.defineProperty all define the property directly, which ignores magic names completely. You get a boring, literal key named __proto__ holding boring, literal data.
That is the opposite of what I expected, and the opposite of advice I have given before. Spread looks reckless and is safe. Object.assign looks like a tidy standard-library call and is not.
Worth saying plainly, because the advice is everywhere: JSON.parse(JSON.stringify(x)) does not sanitize this. It is in the safe group only because it does not trigger the bug. The __proto__ key survives the round trip completely intact, still waiting for the next piece of code that uses assignment.
The copy that lies to you
Look again at the last column for the dangerous group:
const o = JSON.parse('{"name":"ehsan","__proto__":{"isAdmin":true}}')
const copy = {}
for (const k of Object.keys(o)) copy[k] = o[k]
console.log(JSON.stringify(copy)) // {"name":"ehsan"}
console.log(copy.isAdmin) // trueRead those last two lines again. You serialize the object and it looks spotless. You log it, you put it in your error reporter, you paste it into a ticket, and it says {"name":"ehsan"}. Meanwhile the same object answers true to isAdmin.
JSON.stringify only writes down an object’s own properties, and isAdmin is not one — it is on the parent. So the object’s own paperwork is clean and its behaviour is not. If you are debugging this by logging, you will not see it. I spent part of that hour exactly there.
(The matching half of this — what happens when the value is a string instead of an object — behaves differently again, and I wrote that one up separately in the log injection bug a single escaped newline caused.)
Only one of these reaches Object.prototype
Here is the distinction I had completely wrong, and it is the one that decides how scared to be.
Everything in that dangerous group above damages one object. The copy gets a new parent. That is bad, but it is contained — nothing else in your program notices.
To pollute the shared Object.prototype, you need a recursive merge. The kind every config loader and options-merging helper has:
function merge(target, source) {
for (const key of Object.keys(source)) {
if (source[key] && typeof source[key] === "object") {
target[key] = target[key] || {} // <- here
merge(target[key], source[key])
} else {
target[key] = source[key]
}
}
return target
}That marked line is the whole problem. When key is "__proto__", target["__proto__"] does not read a missing property — it reads the object’s actual parent, which is Object.prototype. So target[key] || {} returns Object.prototype itself, and the next line recurses straight into it and writes isAdmin there.
I ran all four in separate, fresh Node processes so none of them could contaminate the next:
| How you copy it | Pollutes global Object.prototype | That one object is broken |
|---|---|---|
| spread | no | no |
Object.assign | no | yes |
| shallow bracket loop | no | yes |
| naive deep merge | yes | yes |
Only the deep merge crosses the line. After it runs:
console.log(({}).isAdmin) // true <- a brand new object you just createdThat is the real thing. Every plain object in the process, including ones created long before the request arrived, now claims isAdmin.
This is why the vulnerability reports you see are almost always against merge, clone-deep, set-by-path and query-string parsers. It is not that those libraries were careless. It is that recursion into an existing property is the only common pattern that walks up into the shared parent instead of just rebinding one object.
Fixing it
Two fixes, depending on where you can intervene.
At the door — drop the key while parsing. JSON.parse takes a second argument, a function that runs for every key as the object is built. Return undefined and the key is left out entirely.
function parseUntrusted(text: string): unknown {
return JSON.parse(text, (key, value) =>
key === "__proto__" || key === "constructor" || key === "prototype"
? undefined
: value
)
}Checked:
const clean = parseUntrusted('{"name":"ehsan","__proto__":{"isAdmin":true}}')
console.log(Object.keys(clean)) // [ 'name' ]
console.log(Object.hasOwn(clean, "__proto__")) // falseThe key is gone — not set to undefined, actually absent. Now no copy method downstream can do anything with it, because there is nothing there. constructor and prototype are in the list because they are a second route to the same parent.
At the loop — define instead of assign. If you cannot control the parse, control the copy:
function copyKeys(source: Record<string, unknown>) {
const out: Record<string, unknown> = {}
for (const key of Object.keys(source)) {
Object.defineProperty(out, key, {
value: source[key],
enumerable: true,
writable: true,
configurable: true,
})
}
return out
}Verbatim keys, no magic doorway, nothing reparented. It is uglier than out[key] = ... and I only use it where the key names come from outside.
And for merge specifically, skip the dangerous names before you recurse. The guard belongs on the key, before the target[key] || {} read — once you have read the parent, it is too late.
What I actually took away
I had been carrying two beliefs that a few minutes of testing destroyed. That JSON.parse is where prototype pollution happens — it is not, it is just where the payload arrives intact. And that spreading an untrusted object is risky while Object.assign is the grown-up version — it is exactly backwards.
The useful question is not “did this data come from outside.” It is “does this line assign to a key whose name I did not write myself.” Spread does not. A loop does. That is the whole test, and it fits in a grep:
grep -rn "\[key\] *=\|\[k\] *=" src/Most hits will be fine. The ones where the key came from a request body are the ones to look at.
If you want the other side of this — how data from a browser gets sanitized before it is ever written to a log — I went through that in the log injection bug, and the same habit of checking a plausible claim against a real process turned up a fetch timeout that starts before the request does. Plausible loses to measured every single time.