EasyFrontend Security📖 Theory Question

What is a Content Security Policy (CSP) and how does it work?

💡

Hint

HTTP header that whitelists sources for scripts, styles, images — blocks injected inline scripts and unknown CDNs

Full Answer

A Content Security Policy is an HTTP response header that tells the browser which sources are allowed to load scripts, styles, images, fonts, etc. Violations are blocked.

Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://cdn.example.com;
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  frame-ancestors 'none';

Key directives:

  • default-src — fallback for all resource types not explicitly listed.
  • script-src — which origins can serve JavaScript.
  • frame-ancestors — which origins can embed this page in an iframe (replaces X-Frame-Options).
  • 'nonce-{random}' — whitelist an inline script by including a per-request nonce: <script nonce="r4nd0m">.
  • 'strict-dynamic' — trust scripts loaded by trusted scripts (allows dynamic script injection from whitelisted scripts).

Reporting: Use Content-Security-Policy-Report-Only header to log violations without blocking — essential when rolling out a CSP to a production app.

💡 Aim for a CSP that eliminates 'unsafe-inline' for scripts. Nonces (Next.js middleware) are the practical way to achieve this with SSR apps.

More Frontend Security Questions

EasyWhat is XSS (Cross-Site Scripting) and how do you prevent it?→EasyWhat is CSRF and how do SameSite cookies and CSRF tokens prevent it?→EasyWhat is clickjacking and how do you prevent it?→EasyWhat security HTTP response headers should every production frontend set?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint