Advertisement
Advanced JavaScript, JSON & Data Serialization

How do you safely parse potentially untrusted JSON without exposing your app to prototype pollution?

Short answer

Standard JSON.parse() itself is safe from prototype pollution since it produces plain data, but code that later merges parsed JSON into existing objects (e.g.

Save JavaScript mock interview
Advertisement
AModel answer
Standard JSON.parse() itself is safe from prototype pollution since it produces plain data, but code that later merges parsed JSON into existing objects (e.g. a naive deep-merge) can be tricked into setting __proto__ or constructor.prototype if you don't explicitly guard against those keys.
function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (key === '__proto__' || key === 'constructor') continue; // guard
    target[key] = source[key];
  }
  return target;
}
Real-world example
Safely merging untrusted JSON configuration from a user upload into an app's settings object.
Likely follow-ups
  • Which popular libraries have had real prototype-pollution vulnerabilities from unsafe JSON merging?
Related topics