React XSS Prevention: Safe HTML & DOMPurify

Why XSS Still Happens in React

React escapes strings by default, but XSS sneaks in via dangerouslySetInnerHTML, user-controlled URLs, third-party widgets, and lax CSP. Here’s a concise, copy-paste guide to XSS prevention in React.js.

React XSS Prevention: Safe HTML & DOMPurify

Quick Wins Checklist

  • Sanitize any HTML before rendering

  • Block javascript:/data: URLs

  • Encode output and attributes

  • Use Content-Security-Policy (CSP)

  • Keep dependencies & React updated


Copy-Paste React Snippets

1) Safe HTML rendering (DOMPurify)

import DOMPurify from 'dompurify';
function SafeHTML({ html }) {
  const clean = DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

2) Never trust URLs (block scripts)

const safeHref = (u) => /^https?:\/\//i.test(u) ? u : '#';
<a href={safeHref(userInputUrl)}>Open</a>

3) Encode text output

function Text({ value }) { return <span>{String(value)}</span>; }

4) Encode attributes

<img alt={String(altText)} src={String(srcUrl)} />

5) Sanitize markdown → HTML

import { marked } from 'marked';
const toHTML = (md) => DOMPurify.sanitize(marked.parse(md));

6) Guard inline styles

const safeStyle = (s) => ({ color: /^[a-z#0-9]+$/i.test(s) ? s : 'inherit' });
<div style={safeStyle(userColor)}>Hello</div>

7) Strict CSP (via Helmet in index.html)

<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests">

8) Server cookies (Express)

res.cookie('sid', v, { httpOnly:true, sameSite:'Strict', secure:true });

(Image) Tool Screenshot

Screenshot of our Free Website Vulnerability Scanner:

Screenshot of the free tools webpage where you can access security assessment tools.
Screenshot of the free tools webpage where you can access security assessment tools.

(Image) Sample Report

Sample Assessment Report generated by our tool to check Website Vulnerability:

Sample vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
Sample vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.

Testing Tips

  • Fuzz inputs with <img src=x onerror=alert(1)> to verify blocks

  • Review dependencies for known XSS (npm audit)

  • Prefer allow-lists to block-lists in sanitizers


Try the Free Scanner

Kick off a scan now: https://free.pentesttesting.com/ — great for catching reflected/stored XSS, CSP gaps, and unsafe headers before release.

More reads: Pentest Testing Corp. Blog → https://www.pentesttesting.com/blog/


Managed IT Services

Harden endpoints, patch faster, and monitor 24/7.
https://www.pentesttesting.com/managed-it-services/

AI Application Cybersecurity

Secure LLM prompts, guardrails, data leakage controls, and model supply chain.
https://www.pentesttesting.com/ai-application-cybersecurity/

Offer Cybersecurity to Your Clients

White-label pentesting & audits for agencies and MSPs.
https://www.pentesttesting.com/offer-cybersecurity-service-to-your-client/

Newsletter

Subscribe on LinkedIn https://www.linkedin.com/build-relation/newsletter-follow?entityUrn=7327563980778995713

Comments

Popular posts from this blog

Fix Sensitive Data Exposure in Symfony Apps

Fix Security Misconfiguration Issues in Symfony

Open Redirect Vulnerability in Symfony