1. Home
  2. Blog
  3. Software Development

Software Development

Content Security Policy Explained: Nonces, strict-dynamic and Report-Only

A content security policy is an HTTP header that tells the browser which scripts, styles, images and other resources a page may load. Done well, it stops most cross-site scripting attacks even when an injection bug slips through. We served eight test pages with different policies to a real Chromium browser and recorded exactly what was blocked and what ran.

9 min read
Content security policy explained: nonces, strict-dynamic and report-only

Key takeaways

  • A content security policy is sent as the Content-Security-Policy response header; the browser enforces it on every resource the page loads.
  • With a nonce-based policy, the inline script carrying the right nonce ran and an identical script without it was blocked.
  • Adding 'strict-dynamic' let our trusted script load another script; without it, the same loader was blocked.
  • Content-Security-Policy-Report-Only reported the violation but let the script run, which is how you test a policy safely.

Cross-site scripting (XSS) happens when an attacker gets their own JavaScript into your page, through a comment field, a URL parameter or a third-party widget. Input escaping is the first defence, but one missed spot is enough. A content security policy (CSP) is a second layer: even if malicious markup reaches the page, the browser refuses to run code that the policy did not approve.

To see the rules in action rather than just describe them, we wrote a tiny Python server that sends eight pages, each with a different policy, and loaded them in a Chromium-based browser. Each page listened for the securitypolicyviolation event and printed what was blocked. The results below are from that run.

What is a content security policy?

CSP is a W3C standard supported by all modern browsers. The server lists trusted sources for each type of resource (scripts, styles, images, fonts, frames, network connections), and the browser blocks everything else, logging a violation. It does not replace secure coding; it limits the damage when something goes wrong, much as HttpOnly cookies limit what a stolen script could read.

How the header works

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self' https://cdn.example.com

A policy is a list of directives separated by semicolons. Each directive names a resource type and its allowed sources: 'self' (same origin), specific hosts, https:, 'none', or keywords such as 'nonce-...' and 'strict-dynamic'. default-src is the fallback for any type you do not list. Keywords must be in single quotes; host names must not.

Our test setup

n = secrets.token_urlsafe(16)          # a fresh nonce for every response
self.send_header("Content-Security-Policy", policy.format(n=n))

# in every page, a nonced listener:
document.addEventListener("securitypolicyviolation",
  e => R.push("blocked " + e.effectiveDirective + " " + (e.blockedURI || "")));

The server generated a new random nonce per response, as a real application must. The violation listener is a useful debugging tool in its own right: it shows the exact directive responsible for each block.

Test 1: inline scripts are blocked

Policy:  script-src 'self' 'nonce-...'
Page:    <script>out.textContent = "inline script RAN"</script>
Result:  inline script did not run
         blocked script-src-elem inline

Once a policy has a script-src without 'unsafe-inline', inline <script> blocks and inline event handlers such as onclick stop working. This is the main protection: most XSS payloads are inline scripts. It is also the main source of breakage when adding CSP to an old site, so expect to move inline code into files or give it a nonce.

Test 2: nonces approve specific scripts

Policy:  script-src 'nonce-...'
Page:    <script nonce="...">...</script>   and   <script>document.title = ...</script>
Result:  nonced script RAN
         blocked script-src-elem inline       (the second script)

A nonce is a random, single-use value placed both in the header and on each trusted script tag. The browser runs a script only if its nonce attribute matches. An attacker injecting markup cannot guess the value, because it changes on every page load. The nonce must be unpredictable (at least 128 bits from a secure random generator) and must never be reused or cached in a shared page. For static sites where you cannot generate nonces per response, use hashes instead: 'sha256-...' of each inline script’s exact content.

Test 3: strict-dynamic trusts scripts loaded by trusted scripts

Policy:  script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'
Page:    nonced script creates <script src="/lib.js"> and appends it
Result:  script loaded by trusted script RAN
         no violations

Real applications load scripts dynamically: tag managers, analytics, code splitting. Giving each of those a nonce is impractical. 'strict-dynamic' passes trust on: any script created by an already-trusted script is allowed too. This is the policy recommended by Google’s web.dev strict CSP guide. With 'strict-dynamic' present, browsers that support it ignore host allowlists and 'self' for scripts, so the nonce becomes the only way in for parser-inserted scripts; we did not run a separate test for that rule.

Test 4: without strict-dynamic, loaders break

Policy:  script-src 'self' 'nonce-...'
Page:    nonced script appends a script from cdn.jsdelivr.net
Result:  library did not load (typeof window._ was undefined)
         blocked script-src-elem https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js

The same loader pattern with only 'self' and a nonce was blocked, because the CDN was not on the list. The old fix is to add every host to an allowlist, but allowlists are weak: research by Google found most allowlist policies could be bypassed through JSONP endpoints or old libraries hosted on allowed CDNs. That is why modern guidance prefers nonces with 'strict-dynamic'.

Test 5: eval is blocked

Policy:  script-src 'nonce-...'
Code:    try { eval("1+1") } catch (e) { ... }
Result:  eval blocked: EvalError
         blocked script-src eval

CSP blocks eval, new Function and string arguments to setTimeout unless you add 'unsafe-eval'. Some older template libraries and source-map tools need eval; prefer replacing them over weakening the policy.

Test 6: images from other origins

Policy:  default-src 'self'; script-src 'nonce-...'
Page:    <img src="https://www.google.com/favicon.ico">  <img src="/pixel.svg">
Result:  external: not loaded, local: loaded
         blocked img-src https://www.google.com/favicon.ico

Because the policy had no img-src, it fell back to default-src 'self', and the external image was blocked. Image and connection rules matter more than they seem: attackers who cannot run scripts sometimes leak data through image URLs or fetch calls to their own server, which img-src and connect-src prevent. See our fetch API guide for how connect-src affects requests.

Test 7: inline styles

Policy:  style-src 'self'; script-src 'nonce-...'
Page:    <p style="color:red">  and  <style>body{background:#eef}</style>
Result:  text colour rgb(0, 0, 0), background transparent
         blocked style-src-attr inline | blocked style-src-elem inline

Both the style attribute and the <style> block were ignored, reported separately as style-src-attr and style-src-elem. Strict style rules break many component libraries and WordPress themes, so most sites allow 'unsafe-inline' for styles while keeping scripts strict. That trade-off is reasonable: injected CSS is far less dangerous than injected JavaScript.

Test 8: Report-Only mode

Header:  Content-Security-Policy-Report-Only: script-src 'self' 'nonce-...'
Page:    un-nonced inline script
Result:  inline script RAN (report only)
         blocked script-src-elem inline      (reported, not enforced)

With the Report-Only header, the browser evaluated the policy and fired the violation, but still ran the script. That lets you deploy a policy to real users, collect every violation it would cause, fix them, and only then enforce it. Add report-to (with a Reporting-Endpoints header) or the older report-uri directive to send reports to a collection endpoint; we observed violations in the page rather than at an endpoint. Report-Only does not work in a <meta> tag, only as a header.

Key CSP directives

Directive Controls
default-src Fallback for types not listed
script-src JavaScript, including inline and eval
style-src CSS files, style blocks and attributes
img-src, font-src, media-src Images, fonts, audio and video
connect-src fetch, XHR, WebSocket and EventSource targets
frame-src What your page may embed in iframes
frame-ancestors Who may embed your page (clickjacking protection)
object-src Plugins; set to 'none'
base-uri Limits the base tag; set to 'none' or 'self'
form-action Where forms may submit
upgrade-insecure-requests Rewrites http resource URLs to https

CSP is separate from CORS: CORS controls which other sites may read your server’s responses, while CSP controls what your page may load and run.

A strict starter policy

Content-Security-Policy:
  script-src 'nonce-{RANDOM}' 'strict-dynamic' https: 'unsafe-inline';
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'self';

This follows the pattern recommended by web.dev and OWASP. The https: and 'unsafe-inline' entries look alarming, but they are fallbacks for very old browsers: browsers that understand nonces ignore 'unsafe-inline' when a nonce is present, and browsers that understand 'strict-dynamic' ignore https:. Generate the nonce on the server for every response and add it to every script tag your templates output.

Tip: if a page is cached by a CDN or a page cache plugin, every visitor gets the same nonce. Either exclude those pages from caching, or use hash-based policies for them.

Rolling out CSP without breaking your site

  1. Inventory scripts, styles, fonts, frames and API hosts the site uses.
  2. Deploy the target policy as Report-Only and collect violations for a week or two.
  3. Fix violations: move inline handlers to files, add nonces, remove eval.
  4. Switch to the enforcing header, and keep a Report-Only copy of a stricter next version running alongside.
  5. Check the policy in your release tests, as part of a security regression checklist.

Common mistakes

  • Using 'unsafe-inline' for scripts without a nonce, which removes most of the XSS protection.
  • Reusing a fixed nonce, which an attacker can simply copy from the page source.
  • Allowlisting large CDNs or *, which lets attackers load any script hosted there.
  • Forgetting object-src 'none' and base-uri, two well-known bypass routes.
  • Leaving Report-Only in place for ever, which reports attacks but never stops them.
  • Setting two conflicting CSP headers, for example one from the app and one from the web server: browsers enforce both, so the result is stricter than either.

Final thoughts

A content security policy turns the browser into an enforcement point: code you did not approve does not run. Our tests showed the essentials. Inline scripts without a nonce were blocked, nonced scripts ran, 'strict-dynamic' let trusted loaders work, eval was refused, and Report-Only mode reported problems without breaking anything. Start in Report-Only, move to a nonce-based strict policy, keep styles a little looser if you must, and test the header in every release.

Frequently asked questions

What does a content security policy do?

It tells the browser which sources of scripts, styles, images and other resources a page may use. Anything else is blocked, which stops most injected scripts from running.

What is a CSP nonce?

A random value generated for each response, placed in the policy header and on every trusted script tag. Only scripts with the matching nonce run, and attackers cannot guess it.

What does strict-dynamic mean in CSP?

It lets scripts that were trusted through a nonce or hash load further scripts, which are then trusted too. Supporting browsers ignore host allowlists for scripts when it is present.

How do I test a CSP without breaking my site?

Send it with the Content-Security-Policy-Report-Only header. The browser reports violations but does not block anything, so you can fix problems before enforcing it.

Can I set a CSP in a meta tag?

Yes, for most directives, but the header is preferred. A meta tag cannot use report-only mode or the frame-ancestors directive.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →