Course contentsShow
← Security
Lesson 1198 of 3,05224. Application Security - Input ValidationFree lesson

Prototype Pollution Prevention Techniques

Implementing Object.create(null), Object.freeze(), schema validation, and safe property access to prevent pollution.

Prototype Pollution Prevention Techniques

What you'll learn: How to protect JavaScript applications from prototype pollution using defensive coding patterns and validation strategies.

Now that you understand how prototype pollution works and how to detect it, let's explore concrete techniques to prevent attackers from injecting malicious properties into your object prototypes.

Core Prevention Strategies

Think of these techniques as building walls around your object prototypes — each layer adds protection against unauthorized modification.

Object.create(null)

Create objects without a prototype chain. This removes __proto__, constructor, and inherited properties entirely:

const safeConfig = Object.create(null);
safeConfig.apiKey = "secret";
// safeConfig has no prototype — pollution impossible

Object.freeze()

Make prototypes immutable so they cannot be modified after creation:

Object.freeze(Object.prototype);
Object.freeze(Array.prototype);
// Any attempt to modify these prototypes now fails silently (or throws in strict mode)

Schema Validation

Validate all input against a strict allowlist before merging:

const allowedKeys = ['name', 'email', 'age'];
function safeMerge(target, source) {
    for (const key in source) {
        if (allowedKeys.includes(key)) {
            target[key] = source[key];
        }
    }
}

Safe Property Access

Always check if a property is the object's own, not inherited:

function safeMerge(target, source) {
    for (const key in source) {
        if (source.hasOwnProperty(key) && 
            key !== '__proto__' && 
            key !== 'constructor' && 
            key !== 'prototype') {
            target[key] = source[key];
        }
    }
}

Combine these techniques for defense-in-depth: use prototype-less objects for sensitive data, freeze critical prototypes, validate all external input, and always verify property ownership.

Key Takeaway: Prevent prototype pollution by using Object.create(null) for sensitive objects, Object.freeze() for prototypes, strict schema validation on inputs, and hasOwnProperty() checks combined with dangerous key filtering during property operations.