React security

From RedHatProductSecurity/prodsec-skills · View interactive version

React security is an AI agent skill from the GitHub repository RedHatProductSecurity/prodsec-skills. Enforce XSS prevention and secure rendering in React applications. Use when building, reviewing, or auditing React components, especially those that render user-controlled data or use server-side rendering.

How to use this skill

Skill file

React Security

React escapes values rendered via JSX data binding by default, but several patterns can reintroduce XSS vulnerabilities. This skill covers the most common pitfalls.

Default Data Binding

React automatically escapes values inside curly braces when rendering text content. This protection does not apply to HTML attributes.

Safe -- text content is escaped:

<div>{userData}</div>

Unsafe -- attribute values are not automatically escaped:

<form action={userData}>...</form>

Always validate or sanitize values placed in HTML attributes, especially href, src, action, and event handler attributes.

dangerouslySetInnerHTML

Never pass unsanitized data to dangerouslySetInnerHTML. Always sanitize with a library like DOMPurify before rendering raw HTML.

Safe:

import DOMPurify from "dompurify";
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(data) }} />

Unsafe:

this.myRef.current.innerHTML = attackerControlledValue;

Direct DOM manipulation via refs bypasses React's escaping entirely.

URL Validation

URLs can contain executable content via javascript: protocol URIs. Validate that URLs use http: or https: before rendering them.

Safe:

function validateURL(url) {
  const parsed = new URL(url);
  return ["https:", "http:"].includes(parsed.protocol);
}

<a href={validateURL(url) ? url : ""}>Click here</a>

Unsafe:

<a href={attackerControlled}>Click here</a>

Server-Side Rendering (SSR)

ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup() provide automatic content escaping for data bound through JSX. Do not concatenate unsanitized data with their output.

Unsafe SSR pattern:

const html = ReactDOMServer.renderToString(<App />) + unsanitizedData;

JSON Injection in Preloaded State

When embedding serialized state in SSR HTML, escape HTML-significant characters to prevent script injection via closing </script> tags.

Safe:

window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, "\\u003c")}

Implementation Checklist

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.