Security & Configuration

Use Content Security Policy as a Practical Defense Layer

Deploy a restrictive Content Security Policy incrementally and understand how directives affect scripts, styles, images, and frames.

Use Content Security Policy as a Practical Defense Layer

Overview

Use CSP reporting and nonce or hash-based script authorization to reduce the impact of injection vulnerabilities.

Start with an inventory

List the origins required for scripts, styles, fonts, images, API connections, frames, and media. Prefer same-origin resources where practical. A policy that blindly allows every source or uses unsafe-inline everywhere provides limited protection. Identify inline scripts and styles that can be moved to external files or authorized with nonces or hashes.

Roll out in report-only mode

Begin with Content-Security-Policy-Report-Only to discover legitimate violations without blocking production behavior. Review reports, remove unexpected dependencies, and avoid collecting sensitive request data in a public reporting endpoint. Then enforce the policy and keep monitoring changes introduced by new integrations.

Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; form-action 'self'

Use per-response nonces where needed

A server-generated unpredictable nonce can authorize specific inline script elements for one response. Generate a new nonce for each response and ensure the same value is placed in the header and approved script tags. Do not reuse a static nonce or expose it in unrelated contexts.

Treat CSP as defense in depth

CSP does not replace output encoding, safe templating, input validation, or dependency review. Test login, search, analytics, payment, and embedded content flows before enforcement. Document why each external origin is allowed and remove permissions that are no longer required.

Implementation checklist

  • Define the expected behavior and supported environments.
  • Keep security, accessibility, and failure states in the design.
  • Measure the result with representative user journeys.
  • Document operational assumptions and review them after changes.
Share this page Help other developers discover this resource.