Skip to content
ProfitTool
Back to all articles
Privacy & Security
1 min read

Content Security Policy (CSP) Explained: How to Prevent XSS

A CSP header tells the browser which scripts, styles and resources it may load, which is what blunts XSS. Directives, nonces, and how to roll one out safely.

ProfitTool Team

Security & Dev

What CSP Does

Cross-Site Scripting (XSS) is one of the most common web vulnerabilities. An attacker injects malicious JavaScript into your page — through a comment field, URL parameter, or compromised dependency — and that script runs in the user's browser, potentially stealing session tokens or data.

A Content Security Policy tells the browser exactly which sources of content are trusted. Even if an attacker manages to inject a script tag, the browser will refuse to execute it if the source is not on the approved list.

The CSP Header

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; style-src 'self' 'unsafe-inline'; img-src * data:

Key Directives

DirectiveControls
default-srcFallback for unspecified directives
script-srcJavaScript sources
style-srcCSS sources
img-srcImage sources
connect-srcfetch(), XHR, WebSocket destinations
font-srcWeb font sources
frame-srcWhat can be embedded in iframes
frame-ancestorsWho can embed this page (replaces X-Frame-Options)
form-actionWhere forms can submit
upgrade-insecure-requestsAuto-upgrade HTTP to HTTPS

Values

ValueMeaning
'self'Same origin only
'none'Nothing allowed
'unsafe-inline'Allow inline scripts/styles — weakens CSP significantly
'unsafe-eval'Allow eval() — avoid if possible
'nonce-abc123'Allow specific inline blocks tagged with nonce
'sha256-hash'Allow specific script by its hash
https://cdn.example.comSpecific external origin

Instead of unsafe-inline, generate a random nonce per request and include it in both the header and the script tag:

<!-- Server generates nonce per request -->
<script nonce="r4nd0m123">/* this script is allowed */</script>
Content-Security-Policy: script-src 'nonce-r4nd0m123'

Since the attacker cannot guess the nonce, injected scripts are blocked.

Report-Only Mode

Start with Content-Security-Policy-Report-Only to log violations without blocking anything:

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report

Review reports, fix legitimate sources, then switch to enforcement mode.

Check your CSP with our Security Headers Checker.

Tags:#csp#content security policy#xss#security headers#web security

ProfitTool Team

Security & Dev

Written and maintained by the ProfitTool team. Where an article references a ProfitTool utility, the behaviour described is the behaviour of the tool on this site — you can open it and check the output yourself.