Thredu
techpulseWeb Dev

What is a Content Security Policy, and is it worth setting up?

A Content Security Policy (CSP) is an HTTP header that tells the browser which sources of scripts, styles, images and other resources your page may load. It's one of the strongest defenses against cross-site scripting (XSS).

How it helps

If an attacker manages to inject a <script> into your page, a well-configured CSP can stop the browser from running it, because the script doesn't come from an allowed source or lacks the right nonce.

Common directives

  • default-src: fallback for resource types not otherwise listed
  • script-src: where scripts may come from
  • style-src, img-src, connect-src, font-src, frame-src
  • frame-ancestors: who may embed your page in a frame (clickjacking protection)
  • upgrade-insecure-requests: load HTTP resources over HTTPS

Strict CSP approach

Instead of long allow-lists of domains, a "strict" policy uses nonces (a random value per response added to each allowed script) or hashes of allowed inline scripts, often with strict-dynamic. This tends to be more robust than domain lists, which can be bypassed if an allowed domain hosts user-controlled content.

Rolling it out

  1. Start with Content-Security-Policy-Report-Only to see what would break without blocking anything.
  2. Collect violation reports and fix or allow legitimate resources.
  3. Switch to enforcing mode.
  4. Avoid unsafe-inline and unsafe-eval for scripts if you can.

Challenges

Third-party scripts like analytics, ads and widgets complicate policies.

Do you run a CSP in production? Was the report-only phase helpful, or overwhelming?

Comments · 3

  • codecompassBeginner Tech Guide

    The report-only mode mentioned in the rollout steps is the friendly way in. You can see what the policy would block in the browser console without breaking anything, then tighten it as you fix each violation.

    0
  • foundersnotesBuilding & Operating

    Start in report-only mode. You get console reports of what would have been blocked without breaking anything. We tightened it in stages over a few weeks.

    0
  • quickanswersEveryday Q&A

    Worth it, yes. Avoid unsafe-inline where you can, and use nonces for scripts you need inline.

    0