Content Security Policy (CSP) Header Generator
A Content Security Policy (CSP) is a browser security standard that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks by controlling which resources a page can load. Use this generator to build, validate, and export production-ready CSP headers.
What is Content Security Policy?
Content Security Policy is an HTTP response header that tells the browser which sources of content are trusted. When a CSP is properly configured, the browser will only execute or render resources from origins explicitly listed in the policy.
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'; upgrade-insecure-requestsCSP is your website's most powerful defense against injection attacks. It acts as a safety net — even if an attacker manages to inject malicious code, CSP can prevent it from executing.
How Browsers Use CSP
When a browser receives a CSP header:
- Parse the policy directives and source expressions
- Evaluate every resource request against the policy
- Block resources that don't match any allowed source
- Report violations to the configured endpoint
This evaluation happens before any resource is loaded, preventing attacks at the earliest possible stage.
How CSP Prevents Attacks
| Attack Type | CSP Protection |
|---|---|
| Cross-Site Scripting (XSS) | Blocks inline scripts unless allowed by nonce or hash |
| Clickjacking | Restricts iframe embedding via frame-ancestors |
| Data Exfiltration | Controls which origins scripts can connect to |
| Base Tag Injection | Locks base URIs via base-uri |
| Mixed Content | Upgrades HTTP to HTTPS via upgrade-insecure-requests |
| Plugin Attacks | Disables plugins via object-src 'none' |
| Form Hijacking | Restricts form submission targets via form-action |
| Supply Chain Attacks | Limits third-party script execution with strict-dynamic |
| DOM XSS | Enforces trusted types via require-trusted-types-for |
Why CSP Matters
Web applications routinely load resources from multiple sources: scripts from CDNs, fonts from Google Fonts, analytics from various providers. This creates a large attack surface. A single XSS vulnerability anywhere in your application can compromise all your users.
CSP reduces this risk by enforcing a whitelist of trusted origins. If an attacker injects a script from an untrusted source, the browser simply refuses to load it.
Key Benefits
- XSS Prevention: Blocks malicious scripts from executing, even if injected into the page
- Clickjacking Protection: Controls whether your site can be embedded in iframes
- Data Exfiltration Prevention: Restricts what domains your page can connect to
- Mixed Content Blocking: Ensures all resources are loaded over HTTPS
- Plugin Restriction: Disables outdated and vulnerable plugin technologies
- Supply Chain Defense: Limits damage from compromised third-party scripts
CSP Levels
CSP Level 1 (2015)
Introduced basic fetch directives: default-src, script-src, style-src, img-src, object-src, frame-src.
CSP Level 2 (2016)
Added navigation directives (base-uri, form-action, frame-ancestors), nonce and hash support for inline scripts, and violation reporting via report-uri.
CSP Level 3 (Current)
Adds granular fetch directives (script-src-elem, script-src-attr), worker-src, manifest-src, trusted-types, report-to, and more.
Feature Highlights
This CSP Header Generator supports all CSP Level 3 directives with real-time output for every major server platform:
Fetch Directives
| Directive | Controls |
|---|---|
default-src |
Fallback source for all resource types |
script-src |
JavaScript execution sources |
style-src |
Stylesheet sources |
img-src |
Image sources |
font-src |
Font sources |
connect-src |
Fetch, XHR, WebSocket, EventSource |
frame-src |
Iframe sources |
frame-ancestors |
Parent frame embedding sources |
object-src |
Plugin sources (object, embed, applet) |
worker-src |
Web Worker and Service Worker sources |
media-src |
Audio and video sources |
manifest-src |
Web App Manifest sources |
prefetch-src |
Prefetch and prerender sources |
Navigation Directives
| Directive | Controls |
|---|---|
form-action |
Form submission targets |
base-uri |
Base URL for relative URLs |
navigate-to |
Document navigation targets |
Document Directives
| Directive | Controls |
|---|---|
sandbox |
Sandbox policy for the page |
upgrade-insecure-requests |
Auto-upgrade HTTP to HTTPS |
block-all-mixed-content |
Block mixed content |
require-trusted-types-for |
Trusted Types enforcement |
trusted-types |
Trusted Types policy names |
Reporting Directives
| Directive | Controls |
|---|---|
report-uri |
Violation report endpoint URL |
report-to |
Modern reporting API group |
Directive Reference
default-src
Serves as the fallback for all other fetch directives. If you set default-src 'self', then script-src, style-src, img-src, etc. will inherit 'self' unless explicitly overridden.
Example:
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.comBest Practice: Always set default-src as your foundation, then override specific directives as needed.
script-src
Controls which sources JavaScript can be loaded from. This is the most critical directive for XSS prevention.
Good:
Content-Security-Policy: script-src 'strict-dynamic' 'nonce-r@nd0m' 'unsafe-inline'Bad:
Content-Security-Policy: script-src 'unsafe-inline' 'unsafe-eval' https:Security Implications: Every script source you add is a potential attack vector. Prefer 'strict-dynamic' with nonces over origin-based allowlists.
style-src
Controls which sources stylesheets can be loaded from. Modern CSS-in-JS libraries require 'unsafe-inline'.
Example:
Content-Security-Policy: style-src 'self' 'unsafe-inline' https://fonts.googleapis.comimg-src
Controls image sources. Typically includes data: for inline images and https: for external images.
Example:
Content-Security-Policy: img-src 'self' data: https:connect-src
Controls which origins the page can make network requests to via fetch(), XHR, WebSocket, and EventSource.
Example:
Content-Security-Policy: connect-src 'self' https://api.example.com wss://ws.example.comfont-src
Controls font sources. Google Fonts requires at minimum the Google Fonts domain.
Example:
Content-Security-Policy: font-src 'self' https://fonts.gstatic.com data:frame-src
Controls which sources can embed the page in frames. Use frame-ancestors for controlling embedding of your site in others.
Example:
Content-Security-Policy: frame-src 'self' https://www.youtube.comframe-ancestors
Controls which origins can embed your page in an iframe. Replaces the older X-Frame-Options header.
Example:
Content-Security-Policy: frame-ancestors 'self'object-src
Controls plugin content via <object>, <embed>, and <applet>. Set to 'none' unless you explicitly need plugins.
Example:
Content-Security-Policy: object-src 'none'base-uri
Restricts the URLs that can be used in a document's <base> element. Prevents attackers from hijacking relative URLs.
Example:
Content-Security-Policy: base-uri 'self'form-action
Restricts the URLs that forms can submit to. Prevents attackers from hijacking form submissions.
Example:
Content-Security-Policy: form-action 'self' https://stripe.comworker-src
Controls Web Worker and Service Worker sources. Critical for preventing malicious background scripts.
Example:
Content-Security-Policy: worker-src 'self' blob:sandbox
Applies a sandbox to the page, restricting what the page can do. Similar to the sandbox attribute on iframes.
Example:
Content-Security-Policy: sandbox allow-scripts allow-same-originupgrade-insecure-requests
Automatically upgrades HTTP URLs to HTTPS. Prevents mixed content warnings and ensures all resources are secure.
Example:
Content-Security-Policy: upgrade-insecure-requestsblock-all-mixed-content
Blocks mixed content entirely (prevents loading HTTP resources on HTTPS pages). More strict than upgrade-insecure-requests.
Example:
Content-Security-Policy: block-all-mixed-contentreport-uri
Specifies where the browser sends violation reports. Use during migration to identify blocked legitimate resources.
Example:
Content-Security-Policy: default-src 'self'; report-uri https://example.com/csp-reportReport-Only Mode
Before enforcing a CSP, you can test it using the Content-Security-Policy-Report-Only header. The browser will report violations without blocking any resources:
Content-Security-Policy-Report-Only: default-src 'self'; report-uri https://example.com/csp-reportThis is the safest way to:
- Discover all resource origins your application uses
- Identify legitimate scripts that would be blocked
- Test new directives before enforcement
- Debug CSP configuration errors
Enforcement Mode
The Content-Security-Policy header enforces the policy. Resources that don't match are blocked by the browser. Always test in Report-Only mode before switching to enforcement.
Browser Compatibility
| Feature | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| CSP Level 1 | ✓ Full | ✓ Full | ✓ Full | ✓ Full |
| CSP Level 2 (nonces, hashes) | ✓ Since 40 | ✓ Since 31 | ✓ Since 10 | ✓ Since 15 |
strict-dynamic |
✓ Since 52 | ✓ Since 52 | ✓ Since 15.4 | ✓ Since 79 |
worker-src |
✓ Since 59 | ✓ Since 58 | ✓ Since 15.4 | ✓ Since 79 |
report-to |
✓ Since 70 | ✓ Since 74 | ✗ | ✓ Since 79 |
trusted-types |
✓ Since 83 | ✗ | ✗ | ✓ Since 83 |
navigate-to |
✗ | ✗ | ✗ | ✗ |
prefetch-src |
✓ Since 86 | ✗ | ✗ | ✓ Since 86 |
Best Practices
1. Start with a Strict Baseline
Begin with default-src 'self' and add exceptions only as needed. A strict policy is always safer than a permissive one.
2. Use Nonces Over Allowlists
Prefer 'nonce-{random}' with 'strict-dynamic' for scripts. This is more secure than listing specific origins.
3. Always Block Plugins
object-src 'none' should be in every policy. Plugins are obsolete security risks.
4. Set Frame Protection
Always set frame-ancestors to prevent clickjacking. Use 'none' for sites that should never be embedded.
5. Lock Down Base URIs
Always set base-uri 'self' to prevent base tag injection attacks.
6. Upgrade Insecure Requests
Use upgrade-insecure-requests as a simple way to prevent mixed content.
7. Test in Report-Only First
Always test your policy with Content-Security-Policy-Report-Only before enforcement.
8. Specify Form Actions
Set form-action to prevent attackers from hijacking form submissions.
9. Be Specific with Sources
Avoid broad sources like https: or *. List only the exact origins you need.
10. Review Regularly
CSP is not "set and forget". Review your policy regularly as your application evolves.
Common Mistakes
❌ Relying on default-src Alone
default-src doesn't cover navigation directives. Always set base-uri, form-action, and frame-ancestors explicitly.
❌ Using 'unsafe-inline' as Default
For scripts, 'unsafe-inline' essentially disables CSP's XSS protection. Use nonces or hashes instead.
❌ Overly Broad Allowlists
script-src https: allows ANY HTTPS origin, including attacker-controlled servers. Be specific.
❌ Forgetting object-src 'none'
Plugins are a major security risk. Always disable them explicitly.
❌ Not Testing Report-Only
Enforcing a CSP without testing in Report-Only mode is the most common mistake. It often breaks legitimate functionality.
❌ Including Too Many Origins
Every additional source in your CSP is a potential attack vector. Keep your allowlist as small as possible.
❌ Exposing Nonces in URLs
Nonces should never appear in URLs or be predictable. They must be unique per request.
❌ Ignoring Violation Reports
If you set a report-uri but never review the reports, you're missing valuable security intelligence.
Security Checklist
Use this checklist to evaluate your CSP:
-
default-srcset to'self'or stricter -
object-srcset to'none' -
script-srcuses nonce or hash (not just'unsafe-inline') -
base-urirestricted to'self'or'none' -
form-actionrestricted to known destinations -
frame-ancestorsset (prevents clickjacking) -
upgrade-insecure-requestsincluded - No wildcard (
*) sources for fetch directives - No broad scheme sources (
https:) -
report-uriconfigured for violation monitoring - Policy tested in Report-Only mode before enforcement
- Nonces regenerated for every request
- Third-party origins validated and minimized
- Inline scripts use nonces or hashes
-
'strict-dynamic'used for modern script management
Migration Strategy
Step 1: Audit
Use the analyzer in this tool (click Analyze) to understand your current CSP posture. Paste existing headers to identify gaps.
Step 2: Report-Only
Deploy your new policy using Content-Security-Policy-Report-Only. This won't block anything but will collect violations.
Step 3: Monitor Violations
Review reports coming from report-uri. Identify legitimate resources being blocked.
Step 4: Adjust Policy
Add necessary exceptions based on real-world violation data. Use the security score in this tool to track your improvement.
Step 5: Enforce
Switch from Report-Only to full enforcement with Content-Security-Policy.
Step 6: Iterate
Regularly review and update your policy as your application evolves. CSP is not "set and forget".
Real-World Examples
Static Website
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requestsSaaS Application (React)
Content-Security-Policy: default-src 'self'; script-src 'strict-dynamic' 'nonce-{random}' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requestsE-commerce
Content-Security-Policy: default-src 'self'; script-src 'self' https://js.stripe.com https://www.google-analytics.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.stripe.com; font-src 'self'; frame-src 'self' https://js.stripe.com; object-src 'none'; base-uri 'self'; form-action 'self' https://api.stripe.com; frame-ancestors 'none'; upgrade-insecure-requestsContent Management (WordPress)
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https:; font-src 'self' data: https:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requestsAPI Server (Express.js)
Content-Security-Policy: default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; connect-src 'none'; font-src 'none'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'FAQ
What is Content Security Policy?
Content Security Policy is an HTTP security header that tells browsers which sources of content are allowed to load on your website. It prevents cross-site scripting (XSS), clickjacking, data injection, and other code injection attacks.
Does CSP stop XSS?
Yes. CSP is one of the most effective defenses against XSS attacks. When properly configured, it blocks inline scripts (unless explicitly allowed via nonces or hashes), restricts script sources to trusted origins, and prevents attackers from executing injected code. However, CSP should be combined with proper input validation and output encoding for defense in depth.
Is CSP required for my website?
CSP is not technically required but is strongly recommended for any website that handles user data, accepts user input, or loads third-party resources. It's considered a security best practice and is included in security standards like OWASP Top 10 and PCI DSS.
What is a CSP nonce?
A nonce (number used once) is a randomly generated token that you add to inline scripts to allow them to execute under CSP. Each request generates a unique nonce value. The nonce is added to both the CSP header ('nonce-r@nd0m') and the script tag (<script nonce="r@nd0m">). Nonces are the recommended approach for allowing inline scripts without weakening security.
What is hash-based CSP?
Hash-based CSP allows you to specify the SHA-256, SHA-384, or SHA-512 hash of specific inline scripts or styles. When the browser encounters an inline script, it computes the hash and compares it to the allowed hashes in the policy. This is useful for scripts that cannot use nonces.
What is Report-Only mode?
Report-Only mode (Content-Security-Policy-Report-Only) lets you test a CSP policy without blocking anything. The browser reports violations to the specified report-uri but allows all resources to load. This is essential for safely deploying CSP to production.
What is 'unsafe-inline'?
'unsafe-inline' allows all inline JavaScript to execute, which significantly weakens CSP's XSS protection. It should only be used as a temporary measure during migration. Prefer nonces or hashes for allowing specific inline scripts.
Can CSP break my website?
Yes, if not properly configured. Testing in Report-Only mode helps identify issues before enforcement. Common problems include blocking legitimate inline scripts, third-party embeds, and API endpoints.
Does CSP impact performance?
No. CSP is evaluated by the browser before resources are loaded. It adds negligible overhead and can actually improve performance by blocking unwanted resources early.
What's the difference between CSP and CORS?
CSP controls which resources a page can load (client-side). CORS controls which origins can access a server's resources (server-side). They solve different but complementary security problems.
What's the difference between frame-src and frame-ancestors?
frame-src controls which origins your page can embed in iframes (loading external content). frame-ancestors controls which origins can embed your page in their iframes (preventing clickjacking).
Do I need CSP if I use HTTPS?
Yes. HTTPS encrypts data in transit but does nothing to prevent code injection attacks. CSP and HTTPS address different security concerns and are complementary.
Does CSP work on mobile browsers?
Yes. CSP is supported in Chrome for Android, Safari on iOS, and Firefox for Android. Mobile browser support matches desktop support for all widely-used directives.
What is 'strict-dynamic'?
'strict-dynamic' allows scripts loaded by an already-trusted script to execute, propagating trust through the script tree. This eliminates the need to list every CDN domain in your CSP while maintaining security.
How do I allow Google Analytics in CSP?
Add https://www.google-analytics.com, https://stats.g.doubleclick.net, and optionally https://www.googletagmanager.com to your script-src, connect-src, and img-src directives.
How do I allow YouTube embeds in CSP?
Add https://www.youtube.com and https://www.youtube-nocookie.com to your frame-src directive.
How do I allow Stripe in CSP?
Add https://js.stripe.com to script-src and frame-src, and https://api.stripe.com to connect-src.
What is the most secure CSP policy?
The most secure policy is as restrictive as possible: default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'. However, this breaks most websites. Balance security with functionality by starting strict and adding only necessary exceptions.
How often should I review my CSP?
Review your CSP policy quarterly, or whenever you add new third-party services, change CDN providers, or update your frontend framework.
Technical Specifications
- Specification: Content Security Policy Level 3
- MDN Reference: MDN CSP Documentation
- Browser Compatibility: Supported in all modern browsers (Chrome, Firefox, Safari, Edge)