Back to results for “Security”
Next.js › Security Best Practices in Next.js

How do you protect a Next.js application against cross site scripting attacks?

Intermediate

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.

Common follow-ups: When is it safe to use dangerouslySetInnerHTML?;What sanitization libraries are commonly used for user generated content?