Frontend System Design · Lesson 11 of 15 · 5 min
Frontend Security Essentials
In an interview, you need to show you can build features that aren't trivially broken. This lesson covers the main attack vectors and how you, on the frontend, can stop them.
Prevent Cross-Site Scripting (XSS)
XSS is what happens when your application renders untrusted user input as HTML, allowing an attacker to execute arbitrary JavaScript in your users' browsers. This is the most common frontend vulnerability.
There are three types you should know:
- Stored XSS: The malicious script is saved in your database (e.g., a user comment) and served to other users.
- Reflected XSS: The script is part of a URL (e.g., in a query parameter) and reflected back in the HTML response, like in a search results page.
- DOM-based XSS: The vulnerability is entirely on the client-side. JavaScript takes data from a source like
window.location.hashand writes it into the DOM without sanitization.
The core defense is to never trust user input. Either escape it or sanitize it before rendering.
- Escaping: Use
textContentorinnerTextinstead ofinnerHTML. This treats all input as plain text, not HTML. This is the safest default. - Sanitization: If you must render user-provided HTML (e.g., for a rich text editor), use a library like
DOMPurifyto parse the input and strip out dangerous elements and attributes.
import DOMPurify from 'dompurify';
// Malicious input from a user comment or URL parameter
const untrustedInput = `Some text <img src="invalid-source" onerror="alert('XSS attack!')">`;
// VULNERABLE: This will execute the script in the onerror attribute.
const vulnerableDiv = document.getElementById('vulnerable-container');
if (vulnerableDiv) {
vulnerableDiv.innerHTML = untrustedInput;
}
// SECURE: DOMPurify removes the malicious onerror attribute.
const sanitizedInput = DOMPurify.sanitize(untrustedInput);
const secureDiv = document.getElementById('secure-container');
if (secureDiv) {
secureDiv.innerHTML = sanitizedInput; // Renders: Some text <img src="invalid-source">
}
The interview question: "You're building a comment section. How do you prevent XSS?" Your answer should start with "By default, I'd render all content using
textContentto treat it as plain text. If rich text is a requirement, I would use a library likeDOMPurifyon the client to sanitize the HTML before rendering, in addition to server-side sanitization as the primary defense."
Defend Against Cross-Site Request Forgery (CSRF)
CSRF tricks a logged-in user's browser into making a state-changing request to your application without their consent. For example, a user visits a malicious site, which contains a hidden form that automatically submits a POST request to /your-app/delete-account. Because the browser automatically sends cookies with requests to your-app.com, the request succeeds.
The primary defense is to ensure that the request was intentionally made by the user. There are two main ways to do this.
1. SameSite Cookies: This is the simplest and most effective defense for modern browsers. By setting the SameSite attribute on your session cookie, you tell the browser when to send it.
SameSite=Strict: The cookie is only sent for requests originating from your own site. This breaks some legitimate use cases, like linking to a page from an external site.SameSite=Lax: The cookie is sent on same-site requests and when a user navigates to your site from an external link (top-level GET requests). It is not sent on cross-originPOSTrequests or requests initiated by scripts. This is the browser default and a good balance of security and usability.
2. CSRF Tokens: For older browsers or more complex scenarios, use CSRF tokens. The server generates a unique, secret token for each user session. The frontend includes this token in a hidden input for forms or as a custom HTTP header (X-CSRF-Token) for API calls. The server validates the token on every state-changing request. An attacker cannot guess this token, so their forged request will fail.
Implement a Content Security Policy (CSP)
A CSP is an HTTP response header that acts as a second line of defense. It tells the browser which sources are allowed to load resources like scripts, styles, and images. A well-configured CSP can block most XSS attacks even if you have a sanitization bug, because the injected script won't be from an allowed domain.
A strict policy might look like this:
Content-Security-Policy: default-src 'self'; script-src 'self'; img-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'
default-src 'self': By default, only allow resources from the same origin.script-src 'self': Only allow scripts from the same origin. This blocks all inline scripts andeval().img-src 'self' https://cdn.example.com: Allow images from the same origin and a specific CDN.
The trap: A weak CSP is worse than none because it gives a false sense of security. Avoid 'unsafe-inline', 'unsafe-eval', and overly broad wildcards like script-src *. Implementing a strict CSP on a large, existing application can be difficult, but it's a powerful security layer.
Choose a Secure Place for Tokens
A common system design question is "How do you store JWTs or other session tokens on the frontend?" Your choice has major security implications.
-
localStorage/sessionStorage: Do not use this for sensitive tokens. Data in local storage is accessible to any JavaScript running on the page. A single XSS vulnerability is all it takes for an attacker to steal the token and impersonate your user. -
In-memory: Storing the token in a JavaScript variable is secure from XSS (as long as your code doesn't expose it). The downside is that the token is lost on page refresh, forcing the user to log in again. This can be acceptable for high-security applications or if you have a refresh token mechanism.
-
HttpOnlyCookies: This is the recommended approach for most web applications. A cookie with theHttpOnlyflag cannot be accessed by JavaScript. The browser handles sending it with each request automatically. Combine this withSecure(only sent over HTTPS) andSameSite=Laxfor a robust defense against both XSS token theft and CSRF.
The main trade-off is that cookies are sent automatically, which is what enables CSRF. But with a SameSite policy, this is largely mitigated. For SPAs that need to know if a user is authenticated, the backend can provide a separate, non-sensitive endpoint like /api/user that returns user info if a valid session cookie is present.
Try it
Review a feature you've recently built that displays data from an API or user input. Identify every place you render that data. Are you using textContent, or are you using innerHTML? If innerHTML, is the source of that data guaranteed to be safe? If not, outline the steps to fix it using DOMPurify.
Next: We'll look at how to structure large applications with Micro-Frontend Architectures.
Lock it in — apply this lesson under interview conditions.