Implement a Deep Merge From Scratch in JavaScript
Write a deep merge from scratch in JavaScript, with plain objects, arrays, prototype pollution protection, no mutation of inputs and tests. Node.js 24.

Object.assign and the spread operator merge one level and stop. Merge { db: { host: "a", port: 1 } } with { db: { host: "b" } } and the second db object replaces the first, taking port with it. A deep merge fixes that by recursing into nested objects, and the interview turns on what recursion should do for arrays, for values that are not plain objects and for keys such as __proto__. That last one is not an academic point: deep merge functions have been the source of real prototype pollution vulnerabilities in widely used libraries. This post builds a safe deepMerge on Node.js 24 and shows each decision with output. For the shallow versus deep copy question in general, see implementing deepClone.
The contract
deepMerge(target, ...sources) returns a new object. Plain objects are merged key by key, recursively. Everything else, including arrays, dates, null and class instances, is replaced by the later value. The inputs are never modified, and later sources win. State these four rules before coding, since they are the specification the tests will check.
What the shallow merge does
const defaults = { db: { host: "localhost", port: 5432 }, debug: false };
const overrides = { db: { host: "prod.example.com" } };
console.log({ ...defaults, ...overrides });{ db: { host: 'prod.example.com' }, debug: false }The port is gone. The spread copied the db key from overrides over the whole db object in defaults, which is exactly the behavior a deep merge exists to avoid.
The first version
function isPlainObject(value) {
if (value === null || typeof value !== "object") return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function deepMerge(target, ...sources) {
let result = target;
for (const source of sources) {
result = merge2(result, source);
}
return result;
}
function merge2(a, b) {
if (!isPlainObject(a) || !isPlainObject(b)) {
return b;
}
const out = { ...a };
for (const key of Object.keys(b)) {
out[key] = key in a ? merge2(a[key], b[key]) : b[key];
}
return out;
}
console.log(deepMerge(defaults, overrides));{ db: { host: 'prod.example.com', port: 5432 }, debug: false }The result keeps port. Walk through the recursion once. At the top, both values are plain objects, so a copy of a is made and each key of b is merged in. For db, both sides are plain objects, so it recurses again: host exists on both and is a string on each side, so merge2 returns b, the later string. port is only in a and survives in the copy.
The helper isPlainObject is doing the important work. It checks the prototype, so a Date, a Map, an array or an instance of a class is not "plain", and is replaced whole. A deep merge that recursed into a Date would produce an empty object, since a date has no own enumerable keys.
const merged = deepMerge({ when: new Date(0), tags: ["a"] }, { when: new Date(1000), tags: ["b"] });
console.log(merged.when.getTime(), merged.tags);1000 [ 'b' ]The date is replaced by the later one, and the array is replaced, not concatenated.
Arrays are a decision, not a default
Arrays are where libraries disagree. Replacing is the simplest rule and the one most configuration systems want: if the override says ["b"], it means ["b"]. Concatenating suits lists that accumulate, such as middleware or plugins. Merging by index almost never does what anyone wants. Pick one, document it and, if you need both, let the caller pass a customizer.
function deepMergeWith(customizer, ...objects) {
const merge = (a, b, key) => {
const custom = customizer(a, b, key);
if (custom !== undefined) return custom;
if (!isPlainObject(a) || !isPlainObject(b)) return b;
const out = { ...a };
for (const k of Object.keys(b)) {
out[k] = k in a ? merge(a[k], b[k], k) : b[k];
}
return out;
};
return objects.reduce((acc, next) => merge(acc, next, undefined));
}
const concatArrays = (a, b) => (Array.isArray(a) && Array.isArray(b) ? [...a, ...b] : undefined);
console.log(deepMergeWith(concatArrays, { plugins: ["a"], n: 1 }, { plugins: ["b"], n: 2 }));{ plugins: [ 'a', 'b' ], n: 2 }The customizer returns undefined to say "no opinion, use the default", which lets it handle arrays and leave everything else alone. Returning undefined as a legitimate merged value is then impossible, a limit worth naming.
Prototype pollution
Now the part that matters for security. Parse a JSON string that has a __proto__ key.
const payload = JSON.parse('{"__proto__": {"isAdmin": true}}');
console.log(Object.keys(payload));
console.log(Object.hasOwn(payload, "__proto__"));[ '__proto__' ]
trueJSON.parse creates an ordinary own property called __proto__, it does not set the prototype. A naive merge that copies keys with target[key] = ... then reaches target["__proto__"], and on a normal object that name is an accessor for the prototype. The line out[key] = merge(out[key], source[key]) reads out.__proto__, which is Object.prototype, merges the attacker's object into it and the whole process now has isAdmin on every object.
function unsafeMerge(a, b) {
for (const key of Object.keys(b)) {
if (isPlainObject(a[key]) && isPlainObject(b[key])) {
unsafeMerge(a[key], b[key]);
} else {
a[key] = b[key];
}
}
return a;
}
unsafeMerge({}, JSON.parse('{"__proto__": {"polluted": "yes"}}'));
console.log({}.polluted);
delete Object.prototype.polluted;yesAn empty object that nobody touched now reports polluted. The two lines at the end undo the damage for the rest of the script, and in a real server there is no such undo until the process restarts. This is how the vulnerability has appeared in popular libraries, and the fix is small.
const UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
function safeMerge(a, b) {
if (!isPlainObject(a) || !isPlainObject(b)) return b;
const out = { ...a };
for (const key of Object.keys(b)) {
if (UNSAFE_KEYS.has(key)) continue;
out[key] = key in a ? safeMerge(a[key], b[key]) : b[key];
}
return out;
}
const poisoned = JSON.parse('{"__proto__": {"polluted": "yes"}, "ok": 1}');
console.log(safeMerge({}, poisoned), {}.polluted);{ ok: 1 } undefinedTwo things protect it. The unsafe keys are skipped. And the function builds a new object and never writes into an existing one, so even a missed key would modify only the copy. key in a also deserves a second look: in finds inherited names, and "toString" in {} is true. Use Object.hasOwn(a, key) instead, so an inherited name is treated as absent.
A stronger option is to build the result on an object with no prototype, Object.create(null), which has no __proto__ accessor at all. The trade-off is that the result lacks hasOwnProperty and friends, which surprises code that calls them directly.
The final version
function deepMerge(...sources) {
return sources.reduce((acc, next) => safeMerge2(acc, next));
}
function safeMerge2(a, b) {
if (!isPlainObject(a) || !isPlainObject(b)) return b;
const out = { ...a };
for (const key of Object.keys(b)) {
if (UNSAFE_KEYS.has(key)) continue;
out[key] = Object.hasOwn(a, key) ? safeMerge2(a[key], b[key]) : b[key];
}
return out;
}
const base = { server: { port: 80, tls: { on: false } }, name: "app" };
const local = { server: { tls: { on: true } } };
const prod = { server: { port: 443 }, name: "prod" };
const result = deepMerge(base, local, prod);
console.log(result);
console.log(base.server.tls.on);{ server: { port: 443, tls: { on: true } }, name: 'prod' }
falseThe three layers merge in order, and the second line confirms that base was not changed. One caution: values that are not plain objects, such as arrays, are copied by reference, so the result shares them with the inputs. Mutating result.tags would also change the source's array. If that matters, copy arrays on the way in with structuredClone, or freeze the inputs.
Configuration is the real use
In practice, deep merge is almost always configuration: defaults, then a file, then environment overrides, then command line flags. That use case explains the rules. Overrides are meant to replace, so arrays are replaced. Unknown keys are kept, so a typo in an override survives the merge and surfaces later as a setting that does nothing. And the order of the sources is the precedence, so the last one wins and the list of sources reads like a stack of layers.
Two habits make this safer. Validate the merged result against a schema, so a misspelled key or a string where a number belongs fails at startup and not in the middle of a request. And log which layer supplied which value when debugging, because the question "why is this port 443?" is the one that merged configuration always produces. A merge that records its source for each leaf is a small extension: carry a second object that stores the layer name, and write to it wherever the value is written.
Finally, remember that merging happens once, at startup. Do not call a deep merge in a hot path, because it allocates a new object per level on every call, and a hot loop that merges options on each request creates garbage for no benefit. Merge once, freeze the result with Object.freeze if you like, and share it.
Where structuredClone helps
structuredClone makes deep copies, not merges, but combining the two gives full isolation: merge, then clone. It is available in Node.js 17 and later, and it handles dates, maps and cycles that a hand-written clone would need extra code for. It throws on functions, which is the reason configuration objects that include callbacks cannot use it.
Testing it
import test from "node:test";
import assert from "node:assert/strict";
test("merges nested objects and keeps unrelated keys", () => {
assert.deepEqual(deepMerge({ a: { b: 1, c: 2 } }, { a: { b: 9 } }), { a: { b: 9, c: 2 } });
});
test("replaces arrays and does not mutate inputs", () => {
const a = { list: [1] };
const b = { list: [2] };
assert.deepEqual(deepMerge(a, b), { list: [2] });
assert.deepEqual(a, { list: [1] });
});
test("ignores __proto__ keys", () => {
deepMerge({}, JSON.parse('{"__proto__": {"x": 1}}'));
assert.equal({}.x, undefined);
});ℹ tests 3
ℹ pass 3
ℹ fail 0

