CSP and security headers
Limit what a browser loads
Content Security Policy (CSP) is a browser-enforced policy delivered in HTTP response headers that can limit resource loading and script execution. A strict policy reduces the impact of some injection mistakes, but does not replace safe coding. Start from application requirements: a bookstore with local assets and no embedded frames needs a different policy from a payment integration.
Interpret a static policy
The example below assumes all needed scripts and assets are served by the same origin and the page must never be embedded. default-src supplies a fallback for applicable resource directives; script-src restricts script sources; object-src disables plugin-style objects. frame-ancestors controls who may embed this page, not which frames it can load, and does not inherit default-src.
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'Deploy with evidence
A report-only CSP can surface candidate violations before enforcement; it does not block them. Test normal page behavior, review reports with privacy filtering and tighten the policy gradually. For applications with inline scripts, consider a framework-supported nonce or hash design. A nonce must be unpredictable and fresh per response; a fixed example is not a production nonce. Avoid broadly allowing inline code just to fix a broken page.
Other headers and remaining controls
Referrer-Policy controls how much referring URL information accompanies requests; no-referrer omits it. X-Content-Type-Options: nosniff helps prevent certain MIME-type interpretation mismatches; send correct Content-Type as well. frame-ancestors can reduce clickjacking risk. None of these headers authorizes users or protects all third-party dependencies. Continue dependency review, input handling and server-side authorization.
Practice: review policy rather than guess
For the example policy, predict whether a same-origin external script is permitted by script-src, whether another origin may embed the bookstore, and whether report-only mode would block a violation. These are policy-reading exercises, not a full browser simulation. In a real approved staging environment, verify legitimate user flows and document any required changes before enforcement.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CSP and security headers — knowledge check
Reason about browser and server controls using fictional cases.
Which directive controls who can embed the page?
What does CSP report-only do?
What should a production CSP nonce be?
Which header can omit referring URL information?
What remains necessary with a strong CSP?