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
60

Frontend System Design · Lesson 60 of 86 · 4 min

Content Security Policy (CSP)

This is how you show an interviewer you can ship secure code, not just talk about it.

Content Security Policy is your most effective defense against Cross-Site Scripting (XSS). In an interview, you need to explain it as a deliberate security strategy, not just a list of headers. The goal is to tell the browser what sources of content are trustworthy, and to block everything else.

An attacker who finds an XSS vulnerability can inject a malicious script. Without a CSP, that script can execute with the same permissions as your own code, stealing session tokens or user data. With a proper CSP, the browser will refuse to load or execute the unauthorized script.

The Core of a Strong Policy

A CSP is an HTTP response header, Content-Security-Policy, containing a set of directives. Each directive controls a resource type. Start with a restrictive default and open up only what you need.

default-src 'self': This is your foundation. It tells the browser that unless another directive says otherwise, resources (scripts, images, styles) are only allowed from your own origin.

script-src 'self' https://cdn.my-app.com: This is the most critical directive for preventing XSS. It specifies exactly where scripts can be loaded from. You'll whitelist your own domain and any trusted CDNs or third-party script providers (like analytics or payment services).

object-src 'none': Always include this. It blocks plugins like Flash, which are a common attack vector. There is rarely a good reason to allow objects today.

frame-ancestors 'self': This directive prevents clickjacking. It controls which origins can embed your page in an <iframe>. 'self' prevents other sites from framing you, while 'none' prevents all framing.

Other useful directives include style-src, img-src, and connect-src (for API calls). Start with default-src 'self' and add more specific rules as needed.

The interview angle: When asked to design a CSP, start with default-src 'self'; script-src 'self' ...; object-src 'none';. This shows you prioritize a locked-down-by-default approach. Then, ask what third-party services the application uses to fill in the rest.

Handling Inline Scripts: The Nonce vs. Hash Trade-off

A strict CSP blocks all inline scripts (<script>...</script>) and event handlers (onclick="...") by default. This is a good thing, as they are a primary XSS vector.

The trap: You might be tempted to add 'unsafe-inline' to your script-src directive to make them work. Don't. It re-opens the very XSS vulnerability you're trying to close. Interviewers will specifically look for you to identify this as an anti-pattern.

You have two secure ways to allow specific, necessary inline scripts:

  1. Nonces (Number used once): The server generates a unique, random string for each request. It includes this nonce in the CSP header and adds it as an attribute to the specific <script> tag it wants to allow. This is best for dynamic, server-rendered pages where the script content might change.

  2. Hashes: You pre-calculate the SHA hash of a static inline script's content. You include this hash in the CSP header. The browser will then execute any inline script whose content hashes to that value. This is best for static inline scripts in SPAs that don't change between requests.

Nonces are more common in server-rendered apps. Hashes are often a better fit for the static HTML shell of a single-page application.

Here is how you would implement a nonce in a Node.js/Express app.

// Server-side (e.g., Node.js with Express)
import express from 'express';
import crypto from 'crypto';

const app = express();

app.use((req, res, next) => {
  // Generate a unique base64-encoded nonce for this request
  const nonce = crypto.randomBytes(16).toString('base64');
  res.locals.nonce = nonce;

  const csp = `
    default-src 'self';
    script-src 'self' 'nonce-${nonce}';
    object-src 'none';
  `;

  res.setHeader('Content-Security-Policy', csp.replace(/\s+/g, ' ').trim());
  next();
});

app.get('/', (req, res) => {
  // In a real app, you'd use a template engine.
  // The 'nonce' is passed to the template.
  res.send(`
    <!DOCTYPE html>
    <html>
    <head><title>CSP with Nonce</title></head>
    <body>
      <h1>My App</h1>
      <!-- This script will execute because its nonce matches the CSP header -->
      <script nonce="${res.locals.nonce}">
        console.log('This trusted inline script is allowed!');
      </script>
      <!-- This script will be blocked because it lacks a matching nonce -->
      <script>
        console.error('This untrusted inline script is blocked!');
      </script>
    </body>
    </html>
  `);
});

app.listen(3000);

Deploying CSP Without Breaking Your App

Rolling out a strict CSP on a live application is risky; you will almost certainly break something. A misconfigured policy can block critical scripts, styles, or images.

The correct strategy is a phased rollout using reporting.

First, deploy your policy using the Content-Security-Policy-Report-Only header. This tells the browser to check the policy and send violation reports to a specified endpoint, but not to actually block the content. This lets you see what a real policy would have broken.

Content-Security-Policy-Report-Only:
  default-src 'self';
  script-src 'self' https://analytics.google.com;
  report-uri /csp-violations;

Your server needs an endpoint (e.g., /csp-violations) that accepts POST requests with these JSON reports. Log them. You'll quickly discover forgotten domains for CDNs, third-party widgets, or browser extensions injecting scripts that you need to account for.

Once your violation reports are clean for a representative amount of time, you can switch the header to Content-Security-Policy to begin enforcement. Keep the report-uri directive to monitor for new violations or attacks.

Try it

Draft a strict CSP for a hypothetical React SPA. The app is served from myapp.com. It loads its JavaScript bundles from cdn.myapp.com, fetches data from api.myapp.com, and uses Google Fonts (fonts.googleapis.com, fonts.gstatic.com). It has one small, static inline script in index.html for setting a theme. Decide whether a nonce or a hash is more appropriate for that script.

Next: Storing Auth Tokens: Cookies vs localStorage

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

CSRF Protection for Frontend Apps

Next

Storing Auth Tokens: Cookies vs localStorage