JAVASCRIPT
Prevent XSS Attacks by Safely Rendering User Input in React
Discover how to prevent Cross-Site Scripting (XSS) vulnerabilities in React applications by safely rendering dynamic, potentially malicious, user-generated content.
import React from 'react';
function CommentDisplay({ commentText }) {
// UNSAFE: Directly rendering user-generated HTML, vulnerable to XSS.
// <div dangerouslySetInnerHTML={{ __html: commentText }} />
// SAFE: React automatically escapes string children, preventing XSS.
// This is the recommended way to display user-generated text.
return (
<div className="comment-bubble">
<h3>User Comment:</h3>
{/* React automatically escapes `commentText` when rendered as a child */}
<p>{commentText}</p>
</div>
);
}
// Example Usage:
function App() {
const maliciousComment = "<script>alert('You are hacked!');</script>Hello there!";
const safeComment = "This is a normal comment with some <b>bold</b> text (which will be escaped).";
return (
<div>
<h2>Malicious Attempt (will be escaped):</h2>
<CommentDisplay commentText={maliciousComment} />
<hr />
<h2>Safe Comment:</h2>
<CommentDisplay commentText={safeComment} />
</div>
);
}
export default App;
How it works: This React snippet illustrates the fundamental principle of preventing Cross-Site Scripting (XSS) attacks by safely rendering user-generated content. Instead of using `dangerouslySetInnerHTML`, which would inject raw HTML and potentially malicious scripts, React's default behavior of treating string children as plain text automatically escapes any HTML special characters. This ensures that scripts embedded in user input are displayed as text rather than executed, mitigating a common XSS vulnerability.