AceDevHub
Advanced JavaScript Interview QuestionsAdvancedScenario

JavaScript · Question 98

What is prototype pollution in JavaScript, and how can applications reduce the risk?

Direct answer

Prototype pollution occurs when untrusted property paths or merge logic modify a shared prototype such as Object.prototype, causing attacker-controlled properties to appear on unrelated objects; prevent it with safe key handling, schema validation, safer data structures, and null-prototype dictionaries where appropriate.

A dangerous generic setter might accept a path like "__proto__.isAdmin" or traverse through constructor.prototype and assign attacker-controlled data. If that reaches a shared prototype, later code may observe obj.isAdmin on objects that never had their own property. The exact exploitability depends on how polluted values are later consumed.

Defenses start by not treating arbitrary attacker-controlled strings as unrestricted object paths. Validate expected schemas, reject dangerous keys where dynamic assignment is unavoidable, and prefer Map for dictionary-like data when prototype inheritance is not part of the model. Object.create(null) can create a dictionary object without Object.prototype in its chain.

  • Use own-property checks when the distinction between own and inherited data matters.
  • Keep dependency versions current because unsafe merge/path utilities have historically been a common vector.
  • Freezing selected prototypes can be defense in depth in controlled environments, but it can break code that intentionally modifies them and is not a substitute for safe input handling.