Content Security Policy Xss Prevention
How to configure Content Security Policy (CSP) correctly: Nonces, strict-dynamic, blocking XSS attacks and preventing injection attacks with modern CSP headers.
Content Security Policy: The XSS Killer
Featured Snippet: Content Security Policy (CSP) is an HTTP response header that tells the browser which resources (scripts, styles, images) are allowed to be loaded from which sources. It is the primary defence mechanism against XSS (Cross-Site Scripting) attacks. Even if attackers inject malicious code, CSP refuses execution. Modern CSP (Level 3) uses Nonces (one-time tokens), strict-dynamic, and Trusted Types for maximum protection. According to Google, CSP blocks 95% of XSS attacks when configured correctly.
Imagine your browser is a nightclub bouncer. CSP is the VIP list. Without CSP, everyone gets in.
The Cost of Inaction: XSS is Ubiquitous
Without CSP, you are vulnerable to the most common web vulnerability.
The Risks:
- XSS Attack Success: Attacker injects
<script>tag via user input (comment, search field). Script steals session cookies -> Account Takeover. - Malicious Scripts: Cryptominers, Keyloggers running in the victim's browser. Slow performance, password theft.
- Third-Party Risks: Compromised ad networks or CDNs inject malware. Without CSP, you have no control.
- Self-XSS Scams: Social Engineering uses XSS. "Copy this code into the console for free coins." CSP blocks this.
Real Example: British Airways was compromised in 2018 via XSS injection in a third-party script. 380,000 credit cards stolen. Fine: β¬20 Million (GDPR). CSP would have prevented this.
The Solution: Defense in Depth with CSP
Layered Security
CSP is no substitute for input validation, but the final line of defence.
The CSP Strategies:
- Strict CSP (Nonce-based): The Gold Standard. Only scripts with a nonce generated by the server are allowed to run.
- Hash-based: For static sites. Every inline script is hashed, only known hashes run.
- Whitelist-based (deprecated): Allows domains like
script-src 'self' cdn.example.com. Susceptible to bypasses.
The Unknown Detail: "Trusted Types API"
The Next Generation
The Problem: Even with CSP, subtle DOM-based XSS can happen.
An attacker uses JavaScript to manipulate innerHTML without injecting a <script> tag.
The Solution: Trusted Types (CSP Level 3).
It enforces that all DOM manipulation APIs (innerHTML, eval, document.write) only accept "trusted" types.
// Without Trusted Types: Dangerous
element.innerHTML = userInput; // XSS possible!
// With Trusted Types: Secure
const policy = trustedTypes.createPolicy('myPolicy', {
createHTML: (string) => DOMPurify.sanitize(string)
});
element.innerHTML = policy.createHTML(userInput); // Sanitized
CSP Header:
Content-Security-Policy: require-trusted-types-for 'script';
Myth-Busting: "'unsafe-inline' is sometimes okay"
β Myth: "I need 'unsafe-inline' for Analytics."
β Reality: "Use Nonces. ALWAYS."
'unsafe-inline' disables CSP completely for scripts. It is like building a door with 10 locks but leaving it open.
Correct Migration:
- Legacy:
script-src 'unsafe-inline'-> Works, but useless. - Modern:
script-src 'nonce-random123'-> Only scripts with this nonce run.
Google Analytics, Facebook Pixel, all modern tools support CSP Nonces. Demand your vendor to do so too.
Expert Insights
Quote 1: CSP is mandatory, not optional
"Any website without Content Security Policy in 2026 is negligent. XSS has been the #1 vulnerability for 20 years. CSP is the only browser-native defence. There is no excuse not to use it anymore."
β Artur Janc, Information Security Engineer at Google
Context: Chrome Security Team.
Quote 2: Report-Only is your friend
"Never activate CSP blindly in Enforcement Mode. Use 'Content-Security-Policy-Report-Only' for at least 2 weeks. Collect Violation Reports. Fix your website. Then activate CSP. Otherwise, you break your own site."
β Scott Helme, Security Researcher
Application: Gradual Adoption.
Implementation: Modern CSP
Strict CSP with Nonces (Best Practice 2026)
Server-Side (Node.js Express Example):
const crypto = require('crypto');
app.use((req, res, next) => {
// Generate random Nonce per request
const nonce = crypto.randomBytes(16).toString('base64');
res.locals.cspNonce = nonce;
// Set CSP Header
res.setHeader(
'Content-Security-Policy',
`script-src 'nonce-${nonce}' 'strict-dynamic' https:; ` +
`object-src 'none'; ` +
`base-uri 'none'; ` +
`require-trusted-types-for 'script';`
);
next();
});
HTML (Inline Script with Nonce):
<script nonce="<%= cspNonce %>">
console.log('This script is allowed');
</script>
<script>
console.log('This script is BLOCKED by CSP');
</script>
Technical Specifications
CSP Directives Overview
| Directive | Purpose | Example |
|-----------|---------|---------|
| default-src | Fallback for all others | 'self' |
| script-src | JavaScript Sources | 'nonce-abc123' 'strict-dynamic' |
| style-src | CSS Sources | 'self' 'unsafe-inline' (okay for CSS) |
| img-src | Images | 'self' data: https: |
| connect-src | Fetch/XHR/WebSocket | 'self' https://api.example.com |
| frame-ancestors | Who can load this page in iframe | 'none' (Clickjacking Protection) |
| upgrade-insecure-requests | HTTP -> HTTPS Upgrade | (no values) |
FAQ: Content Security Policy
How do I debug CSP Violations?
Browser console shows blocked resources. For Production: Use report-uri or report-to directive to send violations to an endpoint. Services like report-uri.com aggregate these reports.
Can I use CSP with a CDN?
Yes, but you must whitelist the CDN domain in script-src. Better: Use Subresource Integrity (SRI) Hashes additionally to ensure the CDN was not compromised.
What is the difference between CSP and CORS?
Completely different. CORS controls which servers can call your API. CSP controls which resources your browser can load. Both important, but orthogonal.
Internal Linking
Related Articles:
MyQuests Team
Founder & Digital Strategist
Olivier Jacob is the founder of MyQuests Website Management, a Hamburg-based digital agency specializing in comprehensive web solutions. With extensive experience in digital strategy, web development, and SEO optimisation, Olivier helps businesses transform their online presence and achieve sustainable growth. His approach combines technical expertise with strategic thinking to deliver measurable results for clients across various industries.
Related Articles
Authentication Best Practices 2026
Read more about this topic Authentication Best Practices 2026 β Web Security & Cyber Resilience
Ddos Protection And Mitigation
Read more about this topic Ddos Protection And Mitigation β Web Security & Cyber Resilience
Encryption Best Practices Data Protection
Read more about this topic Encryption Best Practices Data Protection β Web Security & Cyber Resilience
