Next.js
/Intermediate
XSS Prevention
Definition
Cross-Site Scripting (XSS): A vulnerability where an attacker injects malicious JavaScript into a website, which then executes in the browser of other users.
Explain Like I'm New
An attacker writes `<script>stealPasswords()</script>` in a blog comment. If your website blindly renders that comment, the browser will execute the script. React and Next.js automatically prevent this by 'escaping' all text.
Real World Example
A forum website. You must ensure that if someone pastes JavaScript into a forum post, it displays as raw text on the screen, rather than actually running the code.
Common Use Cases
- •Application security
- •Sanitizing user inputs
Interactive Example
export default function UserComment({ commentText, rawHtml }) { return ( <div> {/* ✅ SAFE BY DEFAULT. If commentText contains <script>alert('Hacked')</script>, React turns it into plain text. It will NOT run. */} <p>{commentText}</p> {/* ❌ EXTREMELY DANGEROUS. This explicitly tells React to execute whatever is in rawHtml as code. Only use this if you ran DOMPurify on rawHtml first! */} <div dangerouslySetInnerHTML={{ __html: rawHtml }} /> </div> ); }
Interview Questions
basic
- Does React automatically protect you from XSS attacks when rendering variables like `<div>{userData}</div>`?
intermediate
- What specific React property explicitly bypasses this protection and leaves you vulnerable to XSS?