Lesson 22 of 30
A response header that tells the browser exactly which sources of scripts, styles, and other resources are allowed to load — a second line of defense that limits an XSS bug's damage even if malicious content sneaks in.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
An XSS bug manages to inject `<script>alert(document.cookie)</script>` directly into the page's HTML. Under a strict CSP with no 'unsafe-inline', does this script execute?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Content-Security-Policy is an HTTP header that gives the browser an allowlist: which origins scripts can load from, which origins images/fonts/styles can come from, whether inline <script> tags are even allowed to run at all.
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; object-src 'none'
This says: by default, only load resources from the same origin; scripts specifically can also come from cdn.example.com; never load any <object>/<embed> content at all. If injected content (from an XSS bug, from the previous lesson) tries to load a script from evil.com, or run inline via <script>alert(1)</script>, the browser refuses — not because the injection didn't happen, but because CSP blocks what that injected content is allowed to do.
Content-Security-Policy: script-src 'self' — an HTTP header, not JavaScript, telling the browser what's allowed to run.
<script>doSomething()</script> written directly in HTML, or an inline onclick="..." attribute, won't run unless you explicitly allow 'unsafe-inline' (which meaningfully weakens the protection) or use a per-request nonce/hash to allow specific, known-safe inline scripts.report-only mode first (Content-Security-Policy-Report-Only), which logs violations without actually blocking anything — the standard way to find out what a strict policy would break before actually enforcing it in production."How would you add a second layer of defense against XSS beyond output escaping?" is exactly the question CSP answers, and knowing it operates at the browser-enforcement level (not the application-code level) shows you understand security as layered defense, not a single fix.