javascript / intermediate
Snippet
Securing Dynamic Prop Spreading Against Prototype Pollution
Spreading unvalidated dynamic objects directly onto React JSX elements can cause Prototype Pollution or unintentional event handler execution. Validating keys with Object.hasOwn and filtering prototype properties prevents object hierarchy poisoning.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';export function SecureDynamicButton({ userSuppliedProps, label }) {const sanitizeProps = (props) => {const safe = Object.create(null);const dangerousKeys = ['__proto__', 'prototype', 'constructor'];for (const [key, value] of Object.entries(props || {})) {if (!dangerousKeys.includes(key) && Object.hasOwn(props, key)) {safe[key] = value;}}return safe;};const safeProps = sanitizeProps(userSuppliedProps);return <button {...safeProps}>{label}</button>;}
react
Breakdown
1
const safe = Object.create(null);
Creates a dictionary object completely free of the default Object.prototype chain.
2
const dangerousKeys = ['__proto__', 'prototype', 'constructor'];
Defines blacklisted property names commonly targeted in prototype pollution exploits.
3
if (!dangerousKeys.includes(key) && Object.hasOwn(props, key)) {
Verifies the key is an own direct property and excludes forbidden prototype modifiers.
4
return <button {...safeProps}>{label}</button>;
Safely spreads only sanitized, validated properties onto the JSX element.