Practical XSS Protection in React: Escaping, Sanitization, and CSP
Prevent cross-site scripting in React by understanding text escaping, dangerous HTML injection, safe URL handling, and Content Security Policy.
TechSilo
Technology writer & developer
Cross-site scripting (XSS) occurs when untrusted input reaches a browser execution context as code. React helps by escaping normal string children, but that protection does not make every data flow or HTML rendering API safe.
What React safely escapes
function Comment({ text }) {
return <p>{text}</p>;
}React treats the string as text, not executable markup. A user submitting HTML-like text does not automatically cause the browser to create those elements.
You still need server-side validation for size and acceptable content. Escaping is a context-dependent output protection, not a complete input policy.
Danger: injecting HTML directly
function Preview({ html }) {
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}If html comes from an untrusted source, malicious markup may create an XSS exposure. Only render sanitized HTML using a maintained sanitizer configured for your allowed tags and attributes. In server-rendered applications, choose a sanitizer suitable for the runtime and verify its output.
Avoid custom sanitizers based only on regular expressions: HTML parsing rules and URL attributes make them unreliable.
URLs are another output context
Do not put arbitrary user-provided strings into href, navigation targets, or redirect URLs without validation.
function safeExternalUrl(value) {
try {
const url = new URL(value);
return ['https:', 'http:'].includes(url.protocol) ? url.href : null;
} catch {
return null;
}
}This rejects non-HTTP URL schemes such as javascript:. For sensitive destinations, allowlist the actual hostnames too. Avoid exposing a general redirect service without additional checks.
Backend XSS risks still matter
If a Node.js template builds an HTML page by concatenating request values, React's escaping does not protect that code. Use templating systems with context-aware escaping, and treat inline event handlers, script contents, and HTML attributes as different security contexts.
Apply Content Security Policy
A Content Security Policy (CSP) can reduce the impact of certain injection bugs by restricting script execution and resource origins. It must be configured to match your framework's legitimate scripts and styles.
Prefer a nonce or hash-based policy for necessary inline scripts rather than allowing all inline JavaScript. Test in report-only mode before enforcing a restrictive policy across an existing site, since a poorly configured policy can break functionality.
CSP is defense in depth; it does not replace safe rendering.
Practical review checklist
1. Search the codebase for dangerouslySetInnerHTML, innerHTML, document.write, and dynamic script creation.
2. Trace every untrusted value that reaches those APIs.
3. Sanitize rich text on the boundary where it must become HTML.
4. Validate URL protocols and permitted destinations.
5. Add browser-focused tests using harmless marker payloads and a test environment.
6. Keep framework and sanitizer packages updated.
XSS prevention is strongest when you avoid HTML interpretation by default and only enable it for intentionally reviewed content. For complementary backend protections, read [Input Validation Strategies](/blog/practical-security-guide-to-input-validation-strategies-mr79jrip).
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Environment Variable Management: Secure Secrets and Deployment Practices
Keep environment configuration safe across local development, CI, and production without leaking API keys into browser bundles or logs.
Read postPractical CORS Configuration Security Guide for APIs
Secure cross-origin browser requests with explicit origin allowlists, correct preflight handling, and credential rules.
Read postAPI Authentication Patterns: Sessions, Tokens, and Service Credentials
Compare session cookies, bearer tokens, OAuth, and API keys, with practical protections against token leakage and authorization mistakes.
Read postPreventing SQL Injection: Parameterized Queries and Safe Database Access
Learn how SQL injection works and how to prevent it using parameterized queries, least-privilege database accounts, and input validation.
Read postFix Next.js Hydration Mismatches: Causes and Safe Solutions
Troubleshoot React hydration errors in Next.js from dates, browser-only APIs, random output, incorrect markup, and third-party libraries.
Read post