Frontend System Design · Lesson 58 of 86 · 4 min
Preventing XSS (Cross-Site Scripting)
In an interview, you need to prove you can build a secure UI, not just a fast one. This is how you articulate a defense-in-depth strategy against XSS.
Cross-Site Scripting (XSS) means an attacker gets their JavaScript to run in your user's browser. Once their code executes, they can steal session tokens, scrape private data, or perform actions on behalf of the user. It's one of the most common web vulnerabilities.
Your job is to make sure that any data originating outside your application is never, ever executed as code.
The Three XSS Attack Vectors
There are three ways an attacker can achieve this. Knowing the difference shows you understand the threat model, not just a single solution.
-
Stored XSS: The attacker saves their malicious script to your server. It gets stored in a database, usually via a form for comments, user profiles, or forum posts. When another user loads a page that displays this data, the script is served from your database and executed in their browser. This is the most dangerous type because one payload can infect many users.
-
Reflected XSS: The script isn't stored. Instead, the attacker crafts a malicious link containing the script (e.g., in a URL query parameter) and tricks a user into clicking it. Your server "reflects" the script from the URL into the HTML response, and the user's browser executes it. A common example is a search page that displays the search query without escaping it:
https://example.com/search?q=<script>alert('xss')</script>. -
DOM-based XSS: The server is not directly involved. The vulnerability exists entirely in your client-side code. Your JavaScript takes data from a source an attacker can control (like
location.hashordocument.referrer) and writes it into the DOM unsafely, using a property likeinnerHTML.
In an interview, don't just list the types. Explain the impact. Stored XSS is high-impact because it's persistent and affects anyone viewing the content. Reflected XSS requires social engineering (phishing) to trick a single user. DOM-based XSS is a bug in your frontend code, pure and simple.
Your Primary Defense: Sanitize All Untrusted HTML
The golden rule is to never trust user input. Modern frameworks like React and Vue help by automatically escaping data you render. If you display "{ "name": "<b>alert('xss')</b>" }" in a template, it renders the literal string, not a bolded alert.
The trap: Developers often need to render rich text (user comments with bolding, links, etc.). To do this, they reach for escape hatches like React's dangerouslySetInnerHTML or Vue's v-html. This bypasses the framework's built-in protection and creates an XSS vulnerability if the HTML isn't sanitized first.
Simple escaping isn't enough for rich text, because it would turn <b> into <b>. You need to sanitize the HTML: parse it, and then allow only a safe list of tags (<b>, <i>, <a>) and attributes (href), while stripping out everything dangerous (<script>, onerror, <iframe>).
Never write your own sanitizer. Use a battle-tested library like DOMPurify.
import DOMPurify from 'dompurify';
// Malicious user-generated content for a comment section
const maliciousRichText = `
<p>This is a great post!</p>
<img src="x" onerror="alert('XSS: image could not load')" />
<a href="javascript:alert('XSS: link was clicked')">Click for a prize!</a>
<p>Check out my <iframe src="https://evil-site.com/phish"></iframe></p>
`;
// Find the element where we'll render the comment
const commentContainer = document.getElementById('comment-section');
if (commentContainer) {
// Sanitize the HTML before inserting it into the DOM.
// DOMPurify parses the HTML, removes dangerous tags and attributes,
// and returns a clean, safe HTML string.
const cleanHTML = DOMPurify.sanitize(maliciousRichText);
// The 'onerror', 'javascript:' href, and 'iframe' are all stripped out.
// Only the <p> and safe parts of <a> remain.
commentContainer.innerHTML = cleanHTML;
}
/*
Expected safe output in the DOM:
<div id="comment-section">
<p>This is a great post!</p>
<img src="x">
<a>Click for a prize!</a>
<p>Check out my </p>
</div>
*/
This is your most important defense. Get this right, and you've stopped most XSS attacks.
Your Second Line of Defense: Content Security Policy (CSP)
Assume a vulnerability slips through. A strong Content Security Policy (CSP) is your next line of defense. It's an HTTP response header your server sends that tells the browser which sources of content are legitimate.
A good CSP can prevent an injected script from executing at all, or block it from sending stolen data to an attacker's server.
A strict policy might look like this:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; connect-src 'self' https://api.example.com; object-src 'none';
This policy says:
default-src 'self': By default, only load resources (images, styles) from my own origin.script-src 'self' https://trusted-cdn.com: Only execute scripts from my origin or fromtrusted-cdn.com. This blocks all inline scripts andeval().connect-src 'self' https://api.example.com: Only allow network requests (fetch, XHR) to my origin orapi.example.com. This prevents an attacker from exfiltrating data to their own server.object-src 'none': Disallow plugins like Flash entirely.
The trade-off: Implementing a strict CSP on a legacy application can be difficult. It forces you to remove all inline scripts (<script>...</script>) and event handlers (onclick="..."). This is a good practice anyway, but requires refactoring. Avoid using 'unsafe-inline' and 'unsafe-eval', as they largely defeat the purpose of the policy.
Mitigating the Impact
Even if an attacker successfully executes a script, you can limit the damage. The most common goal of an XSS attack is to steal the user's session cookie.
Set the HttpOnly flag on your session cookies.
Set-Cookie: session_id=...; HttpOnly; Secure; SameSite=Lax
An HttpOnly cookie cannot be accessed by JavaScript (document.cookie). This single flag means that even if an attacker achieves XSS, they can't steal the session token. They can still perform actions on the user's behalf while the malicious script is running, but they can't hijack the session for later use.
The Secure flag ensures the cookie is only sent over HTTPS, and SameSite is your primary defense against CSRF, which we'll cover next.
Try it
Draft a Content Security Policy for a modern single-page application built with React. Assume it's served from app.example.com, loads its API from api.example.com, and uses a third-party analytics script from https://cdn.google-analytics.com/analytics.js. Justify each directive you choose.
Next: We'll cover how attackers can trick users into performing unwanted actions and how to stop them in CSRF Protection for Frontend Apps.
Lock it in — apply this lesson under interview conditions.