Prevent prototype pollution with constrained object construction
Quick answer
Prototype pollution is an unintended change to a prototype that can influence later property lookups. Avoid merging arbitrary external keys into ordinary objects; construct a known shape and distinguish own properties from inherited ones.
How it works
Allowlist fields and validate their values before constructing a domain object. Object.hasOwn checks ownership even if an object overrides hasOwnProperty. For an arbitrary-key dictionary, Map or Object.create(null) avoids inherited property lookup, but neither makes nested values trustworthy. Avoid unconstrained deep merges. The examples use benign inherited values and known-key copying; they never modify a global prototype.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const x=Object.create({theme:"dark"});x.name="A";console.log(x.theme,Object.hasOwn(x,"theme"),Object.hasOwn(x,"name"));})()Expected console output:
dark false trueOrdinary lookup finds the inherited theme, but own-field validation does not.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {function prefs(x){return {theme:Object.hasOwn(x,"theme")&&["light","dark"].includes(x.theme)?x.theme:"light"};}const y=prefs({theme:"dark",extra:1});console.log(y.theme,Object.hasOwn(y,"extra"));})()Expected console output:
dark falseOnly the validated theme is copied into the output shape.
Common mistakes
Do not assume a property exists on the object itself merely because obj.key returns a value. Do not treat a null-prototype dictionary as complete input validation.
Practice
Copy only a valid own theme field into a new preferences object. Test a valid own field, an extra field and an inherited field.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Prevent prototype pollution with constrained object construction — Knowledge Check
Apply the concept and reason about local example output.
Why prefer explicit field construction to an unrestricted deep merge?
Which check tests whether a property belongs to the object itself?
What additional property must a null-prototype dictionary still satisfy?
What is the exact console output in Prevent prototype pollution with constrained object construction example 1?
(async () => {const x=Object.create({theme:"dark"});x.name="A";console.log(x.theme,Object.hasOwn(x,"theme"),Object.hasOwn(x,"name"));})()What is the exact console output in Prevent prototype pollution with constrained object construction example 2?
(async () => {function prefs(x){return {theme:Object.hasOwn(x,"theme")&&["light","dark"].includes(x.theme)?x.theme:"light"};}const y=prefs({theme:"dark",extra:1});console.log(y.theme,Object.hasOwn(y,"extra"));})()