Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
58

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.

  1. 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.

  2. 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>.

  3. 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.hash or document.referrer) and writes it into the DOM unsafely, using a property like innerHTML.

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 &lt;b&gt;. 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 from trusted-cdn.com. This blocks all inline scripts and eval().
  • connect-src 'self' https://api.example.com: Only allow network requests (fetch, XHR) to my origin or api.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.

Try a free mock interviewPractice system design problems
Previous

CORS: Cross-Origin Resource Sharing

Next

CSRF Protection for Frontend Apps