How do you protect a Next.js application against cross site scripting attacks?
Short answer
React automatically escapes content rendered inside JSX, which prevents most cross site scripting attacks by default, but you should still avoid using dangerouslySetInnerHTML with untrusted content, and always validate and sanitize any user submitted data before storing or…
Advertisement
AModel answer
React automatically escapes content rendered inside JSX, which prevents most cross site scripting attacks by default, but you should still avoid using dangerouslySetInnerHTML with untrusted content, and always validate and sanitize any user submitted data before storing or displaying it.
// React automatically escapes this, protecting against XSS
function Comment({ text }) {
return <p>{text}</p>;
}
// Avoid this unless the content is trusted and sanitized
<div dangerouslySetInnerHTML={{ __html: userInput }} />Real-world example
A comment section on a blog safely displays user submitted text because React automatically escapes it, preventing a malicious visitor from injecting harmful scripts into the page.
Likely follow-ups
- When is it safe to use dangerouslySetInnerHTML?
- What sanitization libraries are commonly used for user generated content?
Related topics