React Security Best Practices: Preventing XSS and Safe Rendering
This article explains how to secure React applications by avoiding dangerous HTML injection methods, using proper sanitization, handling server‑side rendering safely, preventing JSON and URL injection, keeping dependencies up‑to‑date, and applying ESLint security rules.
Hello, I am ConardLi.
Modern front‑end frameworks like React.js and Vue.js already incorporate many security measures, but they cannot completely eliminate vulnerabilities because flexibility always introduces risk.
Below are the best practices to ensure the security of your React applications.
dangerouslySetInnerHTML
React automatically escapes data binding ({}), treating all data as textContent to prevent XSS attacks. However, for flexibility it provides the dangerouslySetInnerHTML property to render raw HTML.
Before using dangerouslySetInnerHTML, ensure the data is filtered or escaped, for example with dompurify.sanitize:
import dompurify from "dompurify";
import "./styles.css";
export default function App() {
const code = "<input onfocus=alert(1) autofocus />";
return (
<div className="App">
<div dangerouslySetInnerHTML={{ __html: dompurify.sanitize(code) }} />
</div>
);
}Avoid Direct DOM Manipulation for HTML Injection
Besides dangerouslySetInnerHTML, you can insert HTML via native DOM API or refs, but these are risky. Prefer React’s declarative approach and avoid direct DOM manipulation unless the data is sanitized.
Using refs to access the DOM for HTML insertion is also dangerous; stick to React’s rendering methods and sanitize any HTML content.
Server‑Side Rendering
When using server‑side rendering functions like ReactDOMServer.renderToString() or ReactDOMServer.renderToStaticMarkup(), automatic content escaping is applied. Avoid concatenating unfiltered data to the output of renderToStaticMarkup() to prevent XSS.
app.get("/", function (req, res) {
return res.send(
ReactDOMServer.renderToStaticMarkup(
React.createElement("h1", null, "Hello ConardLi!")
) + otherData
);
});JSON Injection
When embedding JSON data into a server‑rendered React page, always escape the '<' character to avoid injection attacks:
window.JSON_DATA = ${JSON.stringify(jsonData).replace(/</g, '\u003c')}URL Injection
URL pseudo‑protocols can execute JavaScript. Validate all URLs before injecting them into the DOM and never insert untrusted URLs directly.
import "./styles.css";
function isSafe(url) {
if (url && !url.startsWith("http")) {
return null;
}
// ... other checks
}
export default function App() {
const code = "javascript:alert('xss')";
return (
<div className="App">
Test URL injection
<a href={isSafe(code)}>A harmless link</a>
</div>
);
}Avoid Vulnerable React Versions
Older React versions have known high‑severity security issues; keep React up‑to‑date to avoid these vulnerabilities.
Avoid Vulnerable Third‑Party Dependencies
Open‑source dependencies can introduce security flaws. Regularly audit and update them; see my previous article on dependency security for details.
Therefore, regardless of the framework, regularly updating dependencies is a good practice.
ESLint React Security Configuration
Use the ESLint React security config (https://github.com/snyk-labs/eslint-config-react-security/) to automatically detect risky code patterns.
Conclusion
References:
https://snyk.io/learn/javascript-security/
https://snyk.io/blog/10-react-security-best-practices/
Hope this article helps you.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
