Skip to content
jshacks.dev
Security

Prevent prototype pollution when merging objects

Merge objects without letting __proto__, constructor or prototype keys through, so user JSON cannot change Object.prototype for the whole process.

1 min read
Summarize in AI

A recursive merge that copies keys blindly will follow a __proto__ key from user JSON into Object.prototype, and every object in the process then inherits the attacker's values.

merge.jsJavaScript
function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
    if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
      target[key] = safeMerge(Object.hasOwn(target, key) ? target[key] : {}, source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

const payload = JSON.parse('{"__proto__":{"isAdmin":true},"name":"ana"}');
const result = safeMerge({}, payload);
console.log(result.name, ({}).isAdmin);
Text
ana undefined

JSON.parse creates __proto__ as an ordinary own key, which is why Object.keys sees it and a naive target[key] = ... then writes through the setter. Skipping the three keys and using Object.hasOwn instead of in stops the walk before it reaches the prototype. See the MDN note on prototype pollution.

Skip-lists are easy to get wrong in a deeper path. Where you can, merge into Object.create(null) or a Map, or copy only the keys you declared.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.