SiteTidy
HomeGuidesConfiguring Content Security Policy (Part 1): Build a CSP That Actually Protects You
Security

Configuring Content Security Policy (Part 1): Build a CSP That Actually Protects You

Understand what Content Security Policy really does, how CSP mitigates XSS, why strict nonce/hash policies beat giant allowlists, and how to design a safe baseline without breaking your site.

Published on August 15, 2026Updated August 31, 2026
Configuring Content Security Policy (Part 1): Build a CSP That Actually Protects You

Content Security Policy is one of those web-security controls that looks deceptively simple until you try to deploy it on a real application.

At first glance, it appears to be a header containing a list of domains:

Content-Security-Policy: default-src 'self'

Then production happens.

Your analytics script loads another script. Your payment widget opens an iframe. Your frontend framework injects a style. A marketing tag calls a CDN you did not know it used. Somebody adds 'unsafe-inline' to make the console errors disappear. Six months later the policy is 1,400 characters long, nobody knows which sources are still needed, and everybody assumes “we have CSP” means XSS is solved.

That is not a good CSP.

A useful policy starts with a different question:

Which browser behaviours do we actually want to trust, and how can the browser distinguish those from content an attacker might inject?

This first part establishes that model. Later parts will go deeper into directives, nonces, hashes, strict-dynamic, rollout, reporting, third-party scripts and debugging.

What CSP actually does

Content Security Policy is a browser-enforced security mechanism delivered primarily through the Content-Security-Policy HTTP response header.

The server sends a policy. The browser uses that policy when deciding whether the page is allowed to load or execute resources.

For example:

Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.com

Conceptually, the browser now applies rules like:

Script request?     -> use script-src if present, otherwise default-src
Image request?      -> use img-src if present, otherwise default-src
Font request?       -> use font-src if present, otherwise default-src
Frame request?      -> use frame-src if present, otherwise fallback rules

The important detail is that CSP does not clean malicious HTML and it does not fix unsafe application code.

It constrains what the browser will do with content after the page has been delivered.

That makes it especially useful as a defence-in-depth control against cross-site scripting (XSS).

CSP is a mitigation, not a substitute for output encoding

Suppose an application reflects user input into HTML without escaping it safely:

<div class="welcome">
  Hello, USER_INPUT
</div>

If an attacker can turn USER_INPUT into executable JavaScript, you have an XSS vulnerability.

The primary fix is still to handle untrusted data correctly:

  • context-appropriate output encoding;
  • safe templating;
  • avoiding dangerous DOM sinks;
  • sanitisation where HTML is intentionally accepted;
  • framework security practices.

CSP is the extra browser-side boundary that can make exploitation much harder if unsafe content slips through.

Think of it this way:

Secure application code
        +
Content Security Policy
        =
Stronger XSS resistance

not:

Unsafe application code
        +
CSP
        =
Problem solved

Why script control matters most

CSP can control many resource types, but script execution is the heart of most XSS-focused policies.

If an attacker can inject this:

<script>
  stealSession();
</script>

or this:

<img src=x onerror="stealSession()">

the security problem is not that the page loaded one more file. The problem is that attacker-controlled JavaScript executed in your origin’s security context.

That script may be able to:

  • read page content;
  • act as the logged-in user;
  • access non-HttpOnly tokens or sensitive DOM data;
  • alter payment details;
  • issue authenticated requests;
  • capture keystrokes;
  • inject convincing UI;
  • exfiltrate information to another origin.

A strong CSP therefore tries to establish a trustworthy answer to:

Which scripts are allowed to execute?

The two broad CSP styles: allowlists and strict CSP

There are two common mental models for script policies.

Host allowlist CSP

An allowlist policy says scripts may load from certain locations:

Content-Security-Policy:
  script-src 'self' https://cdn.example.com https://analytics.example.net

This is intuitive and can be useful, but it has a serious weakness: trust is attached to locations rather than individual scripts.

If an allowed origin contains a JSONP endpoint, user-controlled upload path, vulnerable script gadget or other way to serve attacker-influenced JavaScript, the allowlist can be bypassed.

Large real-world allowlists also become difficult to maintain.

Strict CSP

A strict CSP attaches trust to scripts using nonces or cryptographic hashes rather than primarily trusting hostnames.

A nonce-based example:

Content-Security-Policy:
  script-src 'nonce-RANDOM_VALUE' 'strict-dynamic';
  object-src 'none';
  base-uri 'none'

The corresponding trusted script carries the same nonce:

<script nonce="RANDOM_VALUE" src="/app.js"></script>

An injected script without the correct nonce does not execute.

MDN and web.dev both recommend strict nonce- or hash-based policies as the stronger model for XSS mitigation.

Nonces: trust this script on this response

A CSP nonce is a random value generated for a page response.

The server might generate:

q4w0DqQHcV8Vz7qjN1QzVw==

Then send:

Content-Security-Policy:
  script-src 'nonce-q4w0DqQHcV8Vz7qjN1QzVw=='

and render:

<script nonce="q4w0DqQHcV8Vz7qjN1QzVw==" src="/app.js"></script>

The browser compares the two.

If they match, the script may execute.

If an attacker injects:

<script src="https://evil.example/payload.js"></script>

there is no valid nonce, so the browser blocks it.

A nonce must genuinely be unpredictable

Do not use:

nonce="12345"

or:

nonce="20260831"

A nonce should be cryptographically random and newly generated for each response.

web.dev recommends a strong random value, commonly at least 128 bits before encoding.

The important property is not aesthetic randomness. It is that an attacker cannot predict the next value.

Do not automatically add nonces to every script tag

This mistake defeats the purpose.

Imagine middleware that takes the final HTML and blindly changes every script tag from:

<script ...>

into:

<script nonce="CURRENT_NONCE" ...>

If an attacker has already injected a script into that HTML before the middleware runs, their script may receive the trusted nonce too.

OWASP explicitly warns against this pattern.

The application should add the nonce only to scripts it intentionally renders as trusted.

That usually means passing the nonce into a trusted server-side template or framework rendering pipeline.

Hashes: trust this exact script content

For static HTML, generating a different nonce on every response may not fit the hosting model.

Hashes provide another option.

Suppose you have:

<script>
  window.appVersion = "1.2.3";
</script>

You can calculate a SHA-256 hash of the script content and include it in the policy:

Content-Security-Policy:
  script-src 'sha256-BASE64_HASH_HERE'

The browser hashes the inline script and compares it with the allowed value.

If the script changes by even a small amount, the hash changes.

That makes hashes well suited to stable static content, but it creates maintenance overhead if inline script content changes frequently.

A useful rule of thumb:

Server-rendered dynamic HTML -> nonce is often convenient
Static HTML / static builds  -> hashes may fit better

Neither is universally superior.

What strict-dynamic changes

Modern applications often load scripts dynamically.

For example, your trusted application bootstrap may do this:

const script = document.createElement('script');
script.src = '/feature.js';
document.head.appendChild(script);

Without additional policy support, that dynamically loaded script may need its own explicit CSP permission.

'strict-dynamic' lets trust propagate from a nonce- or hash-authorised script to scripts that it loads programmatically.

Example:

Content-Security-Policy:
  script-src 'nonce-RANDOM' 'strict-dynamic';
  object-src 'none';
  base-uri 'none'

This can make strict CSP far more practical for applications using loaders, bundles and third-party bootstrap scripts.

But understand what you are doing: if a trusted script contains a DOM-based XSS bug and uses attacker-controlled data to create another script element, strict-dynamic may allow that child script because the trusted parent created it.

CSP cannot compensate for unsafe logic inside trusted JavaScript.

Why object-src 'none' appears in strict CSP examples

A common strict CSP baseline includes:

object-src 'none'

This blocks resources loaded through legacy plugin-oriented elements such as <object> and <embed>.

Modern applications rarely need those mechanisms.

If you do not need them, explicitly disabling them reduces unnecessary attack surface.

That is why official strict-CSP examples commonly include it even though most developers were originally thinking only about scripts.

Why base-uri 'none' matters

The HTML <base> element can change how relative URLs resolve.

For example:

<base href="https://evil.example/">
<script src="app.js"></script>

The relative app.js may now resolve against the attacker’s base URL rather than your site.

A policy such as:

base-uri 'none'

prevents the page from setting a base URI.

If your application legitimately needs a <base> element, you can use a more appropriate restriction such as 'self' rather than blindly copying 'none'.

What default-src really means

default-src is a fallback for many CSP fetch directives.

Consider:

Content-Security-Policy:
  default-src 'none';
  script-src 'self'

Scripts use script-src 'self' because that directive is explicitly present.

Other applicable resource types fall back to default-src 'none' unless their own directive overrides it.

This is useful for a deny-by-default policy:

Content-Security-Policy:
  default-src 'none';
  script-src 'self';
  style-src 'self';
  img-src 'self' data:;
  font-src 'self';
  connect-src 'self';
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'none'

But do not paste this onto production without testing. If your application loads API calls, fonts, images, frames or styles from other origins, the browser will block them.

A restrictive policy is useful only if it is accurate.

Check the policy your site actually sends

CSP errors are often configuration errors rather than code errors. SiteTidy can inspect the public HTTP response and help you spot missing or weak security headers before you start debugging application behaviour.

Run Free Audit →

Why 'unsafe-inline' is such a warning sign

A script policy containing:

script-src 'self' 'unsafe-inline'

allows inline JavaScript.

That includes patterns CSP is often intended to stop.

For example:

<script>
  doSomething();
</script>

and potentially inline event handlers such as:

<button onclick="doSomething()">Run</button>

Once you permit arbitrary inline script, many injection paths become executable again.

There are compatibility nuances when nonces/hashes and strict CSP are involved, but as a practical review heuristic:

if you see 'unsafe-inline' in an enforcing script policy, find out exactly why it is there.

Do not accept “the site broke without it” as the final answer.

Find the code that broke.

Why 'unsafe-eval' is also dangerous

Some JavaScript libraries and development toolchains use APIs such as eval() or new Function().

A CSP may be loosened with:

script-src 'self' 'unsafe-eval'

That re-enables string-to-code execution APIs that strict CSP normally blocks.

Sometimes a framework’s development build requires it while the production build does not.

This is one reason you should inspect the production application before deciding what CSP permissions are genuinely required.

Do not ship a weaker policy because a local hot-reload tool needed eval().

CSP delivered as a header vs <meta>

CSP can be delivered through an HTTP header, and some CSP functionality can also be expressed using a <meta http-equiv="Content-Security-Policy"> element.

For production, the HTTP response header is generally the stronger and more flexible choice.

For example, report-only mode requires the HTTP header:

Content-Security-Policy-Report-Only: ...

A <meta> policy also cannot protect anything that occurred before the browser encountered the element in the document.

Use meta-based CSP when you have a specific deployment constraint and understand the limitations, not as the default simply because editing HTML is easier than configuring headers.

Enforcement mode vs report-only mode

There are two crucial headers:

Content-Security-Policy: ...

and:

Content-Security-Policy-Report-Only: ...

The first enforces the policy.

The second observes violations without blocking the resources.

That makes report-only extremely useful during rollout.

Suppose you propose:

Content-Security-Policy-Report-Only:
  default-src 'self';
  script-src 'self'

If your application also loads scripts from a payment provider, the browser reports that those scripts would have been blocked, but the payment flow keeps working.

You can collect and analyse violations before enforcement.

Later parts of this series will cover a safe rollout process in detail.

CSP violations do not automatically mean attacks

This is important when you start collecting reports.

A CSP violation may come from:

  • a genuine injection attempt;
  • a browser extension;
  • an outdated application path;
  • a forgotten analytics script;
  • a third-party widget;
  • a malformed browser request;
  • code you intentionally deployed but forgot to allow;
  • a policy that is simply wrong.

Do not wire every violation directly into the pager.

CSP reporting is telemetry. It needs filtering, aggregation and investigation context.

A realistic first policy is better than a fantasy policy

Developers sometimes publish a perfect-looking header in documentation:

Content-Security-Policy:
  default-src 'none';
  script-src 'nonce-abc' 'strict-dynamic';
  style-src 'none';
  img-src 'none';
  connect-src 'none';
  font-src 'none';
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'none'

It is very restrictive.

It also describes a website that does almost nothing.

A production CSP should be strict and compatible with the application.

That requires inventorying real behaviour:

  • which scripts execute;
  • which APIs the browser calls;
  • which third-party widgets are genuinely required;
  • which resources are dynamic;
  • whether the site is server rendered or static;
  • whether inline scripts/styles can realistically be removed;
  • whether you control the HTML rendering pipeline.

Do that inventory before enforcement.

CSP is not your only browser capability boundary

CSP answers questions such as where scripts may execute from and which origins may be framed. It does not decide whether a document may use powerful browser APIs such as camera, microphone or geolocation.

That adjacent job belongs to Permissions Policy. If your application embeds video, maps or other capability-heavy third-party content, review the two policies together rather than assuming a correct frame-src rule also controls what the embedded document can do.

A sensible starting process

If I were adding CSP to an existing production application, I would not begin by writing the final policy.

I would begin by observing the application.

  1. Inventory scripts, styles, images, fonts, frames and network destinations.
  2. Decide whether a nonce-based or hash-based strict CSP fits the rendering architecture.
  3. Build a proposed policy.
  4. Deploy it using Content-Security-Policy-Report-Only.
  5. Exercise real user journeys.
  6. Analyse violations and remove unnecessary dependencies.
  7. Enforce only after the important flows are clean.

That process is slower than copying a header from a generator.

It also gives you a policy you understand.

The standard I would aim for

For a modern application where you control the rendering pipeline, I would generally aim toward a nonce- or hash-based strict script policy rather than a giant hostname allowlist.

That does not mean every application can jump there immediately.

Legacy applications may have hundreds of inline handlers. Third-party vendors may require awkward exceptions. Some frameworks need configuration changes. Static hosting changes the nonce equation.

The right progression is:

Understand current behaviour
        ↓
Report-only policy
        ↓
Remove unnecessary unsafe patterns
        ↓
Introduce nonces/hashes where appropriate
        ↓
Enforce
        ↓
Monitor and maintain

A CSP that is slightly less elegant but actually deployed and maintained is more valuable than a perfect policy sitting in a security ticket for eighteen months.

What comes next

Part 2 will break down the major CSP directives and their fallback behaviour in more detail.

From there, the series will cover strict CSP implementation, third-party scripts, reporting, rollout and the awkward cases that appear in real applications.

The objective is not to collect directives.

It is to end up with a policy you can explain, test and maintain.

Primary references

Ready to audit your site?

Put this guide into practice immediately using our free tools.

Browse 180+ Free Tools