Skip to main content
GuideBest practicesBeginner

Content Security Policy (CSP): reduce XSS risks and unwanted loads

Learn how to introduce a CSP progressively, understand its main directives, Report-Only mode, nonces and common mistakes.

Published 29 August 2026Reading : 1 minBy Yann Bastien
Show contents
  1. Begin with observation
  2. Understand the main directives
  3. Inline code, nonces and hashes
  4. CSP complements application security
  5. Roll out progressively

Content Security Policy tells the browser which origins may provide scripts, styles, images, fonts, frames and network connections. Its main value is to reduce what injected markup can execute or load.

Begin with observation

A strict policy deployed in one step can break a real site. Inventory first-party and third-party resources, then use Content-Security-Policy-Report-Only to observe violations without blocking them. The CSP generator helps build a starting policy.

Understand the main directives

default-src provides a fallback. script-src and style-src deserve special attention because executable code and inline content are frequent sources of risk. img-src, font-src, connect-src, frame-src and object-src narrow other capabilities. Prefer explicit origins over broad wildcards.

Inline code, nonces and hashes

Allowing 'unsafe-inline' weakens an important CSP benefit. When inline code is unavoidable, nonces or CSP hashes can authorize specific blocks instead of all inline execution. A nonce must be unpredictable and generated for each response.

CSP complements application security

CSP does not sanitize untrusted HTML and does not repair broken authorization. Treat it as defense in depth. Combine it with secure coding, HTTPS and the security headers.

Roll out progressively

Start with reporting, remove unnecessary exceptions, test critical journeys, then enforce the policy. Revisit it when analytics, advertising, fonts or other third-party services change. Document every exceptional origin so the policy does not slowly become an unrestricted allow-list.

Was this article useful?