hardBackend

What is prototype pollution and how do you prevent it in Node.js?

317 views
01

Understand the problem

Polluting Object.prototype via proto in merges.

nodejssecurityprototype-pollutionvalidation
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Vulnerable merge vs guarded merge
// ❌ vulnerable: copies __proto__ into the prototype chain
function merge(t, s) { for (const k in s) t[k] = (typeof s[k]==='object') ? merge(t[k]??{}, s[k]) : s[k]; }

// ✅ guard dangerous keys
const BAD = new Set(['__proto__', 'constructor', 'prototype']);
function safeMerge(t, s) {
  for (const k of Object.keys(s)) {
    if (BAD.has(k)) continue;
    t[k] = (s[k] && typeof s[k] === 'object') ? safeMerge(t[k] ?? {}, s[k]) : s[k];
  }
  return t;
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.