javascript / expert
Snippet
Mitigating Prototype Pollution in Deep React State Hydration Objects
When restoring external state in React applications (such as SSR rehydration or localStorage sync), attackers can inject malicious properties into Object.prototype. Using dictionary objects without prototype chains and explicitly checking forbidden property keys neutralizes prototype pollution threats.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function safeHydrateState(target, source) {const cleanTarget = target ?? Object.create(null);for (const key of Object.keys(source)) {if (key === '__proto__' || key === 'constructor' || key === 'prototype') {continue;}const val = source[key];if (val && typeof val === 'object' && !Array.isArray(val)) {cleanTarget[key] = safeHydrateState(cleanTarget[key], val);} else {cleanTarget[key] = val;}}return cleanTarget;}
react
Breakdown
1
const cleanTarget = target ?? Object.create(null);
Instantiates a prototype-less object using Object.create(null) to prevent inheritance lookup exploits.
2
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
Filters out dangerous object property keys that can manipulate the root Object prototype during recursive merges.
3
cleanTarget[key] = safeHydrateState(cleanTarget[key], val);
Recursively merges nested object trees while retaining property isolation rules.