Skip to Content

Prototype Pollution in JavaScript: Examples and Prevention

How __proto__ and constructor.prototype end up in Object.prototype, what attackers do with it in the browser and in Node.js, and how to prevent it
January 4, 2026 by
Prototype Pollution in JavaScript: Examples and Prevention
Ibrahim Zakaria

Prototype pollution in JavaScript is a vulnerability where an attacker sends data with a key such as __proto__ or constructor.prototype, and your code copies it into Object.prototype, the object that almost every other object inherits from. After that, every object in the application "has" the attacker's property. This article shows how it happens with short examples, what it leads to in the browser and in Node.js, and how to prevent it.

The prototype chain in two minutes

Every JavaScript object has a hidden link to another object, its prototype. When you read a property, JavaScript looks at the object first. If the property isn't there, it follows the link to the prototype, then to that object's prototype, until it reaches Object.prototype at the top.

const user = { name: "Rana" };
user.name;        // "Rana" (own property)
user.toString;    // found on Object.prototype
Object.getPrototypeOf(user) === Object.prototype;  // true
user.__proto__ === Object.prototype;               // true

Two paths lead back to Object.prototype from any plain object. One is the __proto__ accessor, and the other is constructor.prototype, because user.constructor is Object. Anything written to Object.prototype shows up when you read that property on any object that doesn't define it itself.

How prototype pollution happens

The bug almost always sits in code that walks through keys it received from outside and writes them into an object. Three patterns come up again and again: recursive merge or deep clone, "set a value by path" helpers, and query-string or form parsers that turn a[b][c]=1 into nested objects.

Example 1: an unsafe deep merge

This is the kind of helper that combines default settings with settings sent in a request:

function merge(target, source) {
  for (const key in source) {
    if (typeof source[key] === "object" && source[key] !== null) {
      if (typeof target[key] !== "object" || target[key] === null) {
        target[key] = {};
      }
      merge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

// The request body, parsed from JSON
const body = JSON.parse('{"__proto__": {"isAdmin": true}}');
merge({}, body);

const someoneElse = {};
someoneElse.isAdmin;  // true

JSON.parse turns "__proto__" into an ordinary key. When the merge reaches it, target["__proto__"] returns Object.prototype, so the next level of the merge writes isAdmin straight into it. Now picture a permission check further down the code:

if (user.isAdmin) {
  // show the admin panel
}

Any user object without its own isAdmin property now passes the check. No error is thrown and nothing appears in the logs.

Example 2: set by path with constructor.prototype

Blocking the string __proto__ isn't enough. A helper that sets a value from a dotted path can be reached through constructor as well:

function setByPath(obj, path, value) {
  const keys = path.split(".");
  let current = obj;
  for (let i = 0; i < keys.length - 1; i++) {
    current[keys[i]] = current[keys[i]] || {};
    current = current[keys[i]];
  }
  current[keys[keys.length - 1]] = value;
}

setByPath({}, "constructor.prototype.isAdmin", true);
({}).isAdmin;  // true

{}.constructor is the Object function, and Object.prototype is the shared prototype, so the last write lands in the same place as before.

Prototype pollution examples in popular libraries

Well-known npm packages have shipped exactly these patterns, which is why the issue gets so much attention:

  • lodash: merge, mergeWith and defaultsDeep could be polluted in older 4.17.x versions (CVE-2018-16487, CVE-2019-10744), and zipObjectDeep later had its own fix (CVE-2020-8203).
  • jQuery: $.extend(true, {}, input) could pollute Object.prototype before version 3.4.0 (CVE-2019-11358).
  • minimist: the command-line argument parser used by many build tools accepted --__proto__.x style arguments before version 1.2.6 (CVE-2020-7598, CVE-2021-44906).
  • Kibana: a prototype pollution flaw in its Timelion feature was chained into remote code execution on the server (CVE-2019-7609).

Old versions of these packages still turn up inside lock files, bundled front-end code and copied snippets, years after the fixes.

What an attacker can do with it

Polluting the prototype is only the first step. The damage depends on what the rest of the code, including your libraries, reads from objects that don't set that property themselves. Security researchers call such code a "gadget".

In the browser

Client-side pollution usually comes from the URL, for example ?__proto__[transport_url]=data:,alert(1) or a hash fragment parsed into an object. If a script on the page later reads an option such as a script URL or an HTML template from a config object that doesn't define it, the attacker's value is used. That leads to DOM-based cross-site scripting (XSS), which can steal sessions or act as the logged-in user.

On the server (Node.js)

Server-side pollution is more serious, because the polluted prototype lives in a process that handles every user's requests until it restarts.

  • Privilege escalation: permission flags such as isAdmin or role become true for everyone.
  • Denial of service: overwriting a property the framework depends on, such as toString or a response option, can break every request.
  • Remote code execution: some libraries pass option objects to child_process or to template engines. A polluted option like shell or an environment variable can turn into running commands on the server, as the Kibana case showed.

How to prevent prototype pollution

No single measure covers everything, so combine several of these.

1. Write merge and set functions that skip dangerous keys

Only copy the object's own keys, and refuse the three names that lead to a prototype:

const BLOCKED = new Set(["__proto__", "constructor", "prototype"]);

function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (BLOCKED.has(key)) continue;
    const value = source[key];
    if (value && typeof value === "object" && !Array.isArray(value)) {
      if (!Object.hasOwn(target, key) || typeof target[key] !== "object" || target[key] === null) {
        target[key] = {};
      }
      safeMerge(target[key], value);
    } else {
      target[key] = value;
    }
  }
  return target;
}

Better still, use an allow-list. If a settings object can only contain theme, language and pageSize, copy those three keys and ignore the rest.

2. Validate input against a schema

Validate every request body before you use it, with a schema library such as Ajv (JSON Schema with additionalProperties: false) or Zod in strict mode. Unknown keys, __proto__ included, are rejected before your code ever sees them.

3. Use objects without a prototype, or a Map

When keys come from users, store them where there's no prototype to reach:

const lookup = Object.create(null);   // no Object.prototype behind it
lookup["__proto__"] = "just a key";

const sessions = new Map();           // keys never touch the prototype
sessions.set(userInput, data);

4. Check own properties for security decisions

Read permission flags in a way inherited values can't satisfy, for example Object.hasOwn(user, "isAdmin") && user.isAdmin === true, or load roles from the database each time instead of from a merged object.

5. Lock the prototype

Object.freeze(Object.prototype) at application start stops any later write to it. Test it first, because a few older libraries add methods to built-in prototypes and will break. In Node.js, the --disable-proto=delete or --disable-proto=throw flag removes the __proto__ accessor. It doesn't stop the constructor.prototype route, so treat it as an extra layer.

6. Keep dependencies up to date

Run npm audit or a dependency scanner in your build, and update lodash, jQuery, minimist and any query-string or deep-merge package they flag. Check the lock file too, because a vulnerable copy often arrives as a dependency of a dependency.

How to test for prototype pollution

  • Unit tests: feed your merge, clone and set-by-path helpers the payloads {"__proto__": {"polluted": 1}} and "constructor.prototype.polluted", then assert that ({}).polluted is still undefined.
  • In the browser: open a page with ?__proto__[polluted]=1 or #__proto__[polluted]=1 added to the URL, then type Object.prototype.polluted in the console. PortSwigger's DOM Invader, built into Burp Suite's browser, automates this and looks for gadgets.
  • On a Node.js server you own: PortSwigger documents non-destructive checks for Express apps, such as sending a json spaces property inside __proto__ and watching whether the indentation of later JSON responses changes. Run these against a test environment, because a successful test pollutes the running process.
  • Static analysis: Semgrep, CodeQL and Snyk Code have rules for recursive merges and dynamic property writes, which is where most of these bugs sit.

Why AI-generated code repeats the pattern

Ask an AI assistant for a "deep merge", a "set nested value by path" helper or a small query-string parser and you'll often get the plain for...in version shown in example 1, because that's the version it has seen most often. It rarely adds a key check unless you ask for one. Assistants also suggest package versions from their training data, which may be older than the fixed releases. And the tests they write feed in friendly data, so nobody tries __proto__ until an attacker does. If a large part of your code was written with AI tools, prototype pollution is one of the first things worth checking. We cover the other common problems in AI-built apps, from exposed keys to open databases, in the security risks of AI-generated code.

Frequently asked questions

Does JavaScript have vulnerabilities?

The language itself is stable, but the way it works makes some mistakes easy to make. Prototype pollution comes from JavaScript's prototype inheritance, and it sits next to other common issues in web apps such as cross-site scripting, unsafe use of eval and outdated npm packages with known CVEs.

What is Object.prototype in JavaScript?

It's the object at the top of the prototype chain. Plain objects inherit methods such as toString and hasOwnProperty from it, so a property added to Object.prototype is visible on every plain object that doesn't define that property itself.

Is prototype pollution only a Node.js problem?

No. It happens in browsers too, usually through URL parameters parsed into objects, where it can lead to cross-site scripting. On a Node.js server the impact is wider, because one polluted process serves all users and can lead to privilege escalation, crashes or, with some libraries, remote code execution.

Does Object.freeze(Object.prototype) fully prevent it?

It blocks writes to Object.prototype, which stops the most common form of the attack. Other built-in prototypes, such as Array.prototype, would need freezing too, and some older libraries break when prototypes are frozen. Combine it with input validation and safe merge functions.

Is lodash merge still vulnerable?

The known prototype pollution issues in merge, mergeWith and defaultsDeep were fixed in lodash 4.17.11 and 4.17.12, and zipObjectDeep in 4.17.20. Use 4.17.21 or later, check your lock file for older nested copies, and still validate data before you merge it.

How do I know if my application is affected?

Search your code and dependencies for recursive merge, clone and set-by-path functions that handle user data, run npm audit, and try the payloads above in a test environment. For a large or AI-generated codebase, an external code review is the faster route.

Get your JavaScript code checked

Prototype pollution is easy to miss in code review because the vulnerable helper looks harmless and the damage shows up somewhere else. Our AI code assessment reviews an application, whoever or whatever wrote it, for security, best practices, maintainability and production readiness. Each finding comes with the steps to reproduce it and what to fix.

For a first look at the basics of an app built with AI, such as secrets, permission checks and outdated libraries, our free self-check asks ten questions and takes about two minutes. Take the self-check →

If you'd like to know where your application stands, book a free 30-minute call and tell us about your stack.

Prototype Pollution in JavaScript: Examples and Prevention
Ibrahim Zakaria January 4, 2026
Share this post
WhatsApp usAI agent replies 24/7
Book a free 30-minute call