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