CSP Generator
Build a strong CSP header with our visual editor. Start with a preset for your platform, customize per directive, and copy-paste the result into Nginx, Apache, Express, Next.js, Vercel, or Django. Free, no signup required.
CSP is the single most effective HTTP header against Cross-Site Scripting (XSS) attacks. It tells the browser exactly which sources can load scripts, styles, and other resources. Anything not in the policy gets blocked.
Quick presets
Start with a preset tuned for your stack, then customize. Each preset balances security with compatibility for the platform.
Directives
Generated CSP header
default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'none'; media-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
Copy-paste examples
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'none'; media-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'none'; media-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
'default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'none'; media-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none''
);
next();
});const securityHeaders = [
{
key: 'Content-Security-Policy',
value: `default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'none'; media-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'`
}
];
module.exports = {
async headers() {
return [{ source: '/(.*)', headers: securityHeaders }];
}
};{
"headers": [{
"source": "/(.*)",
"headers": [{
"key": "Content-Security-Policy",
"value": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'none'; media-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
}]
}]
}# settings.py. Use django-csp:
# pip install django-csp
CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'",)
CSP_OBJECT_SRC = ("'none'",)Replace Content-Security-Policy with Content-Security-Policy-Report-Only to log violations without blocking anything. Monitor your browser console or a reporting endpoint to find resources that need to be added before switching to enforcement mode.
Reading the header you just generated
The default selection, the Strict preset, produces this:
default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:;
font-src 'self'; connect-src 'self'; frame-src 'none'; media-src 'self';
object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'Read it one directive at a time and ask what will break on your site:
script-src 'self'allows only script files from your own origin. Every inline<script>block and everyonclick=attribute stops working. So does any analytics or chat widget loaded from another domain, until you add that domain.style-src 'self'blocks inlinestyle=attributes and<style>tags. Many component libraries inject styles at runtime, which is why every other preset here adds'unsafe-inline'tostyle-src.img-src 'self' data:keeps base64 images working. A CDN or an avatar service needs its own entry.connect-src 'self'is the one people forget. It governsfetch, XHR and WebSockets, so an API on a subdomain or a third-party analytics endpoint will fail silently.frame-ancestors 'none'means no site can embed yours in an iframe, your own included. Use'self'if you embed your own pages.form-action 'self'stops forms posting to another origin. A payment provider's hosted form needs its domain listed here.
Ship it in Report-Only first
We learned the "fail silently" part the hard way. Our own CSP blocked PostHog's script and its data endpoint, and the dashboard showed zero pageviews for 90 days. No visitor ever saw an error.
Deploying the same policy under a different header name avoids that:
Content-Security-Policy-Report-Only: <the generated policy>The browser enforces nothing and reports every violation in the DevTools console. Click through your key pages, including login, checkout and any page with an embed, and add the sources that show up. Then switch the header name to Content-Security-Policy.
To confirm what is live:
curl -sI https://example.com | grep -iE '^content-security-policy'What real policies look like
Out of 2,211 sites in our May 2026 research run, 933 returned headers we could read and weren't flagged by our filter as a bot-protection or error page (internal data from ismycodesafe, how we filtered). 191 of the 933 sent a Content-Security-Policy. This is what those 191 did with it:
| What the policy did | Sites |
|---|---|
No script-src or default-src at all, so no control over scripts | 113 |
Controls scripts, but allows 'unsafe-inline' without a nonce or hash | 55 |
Controls scripts with a nonce or hash, but also allows 'unsafe-eval' or a scheme like https: | 8 |
Controls scripts with none of 'unsafe-inline', 'unsafe-eval', *, https:, http: or data: | 15 |
Fifteen of 933 sent a script policy close to what the Strict preset generates. And 113 of the 191 that "have CSP", about 60 percent, never mention scripts at all. Their header is there for framing rules or HTTPS upgrades. The theory behind each directive is in the Content-Security-Policy guide.
CSP implementation by framework
Next.js (App Router)
Next.js supports CSP via middleware for dynamic nonce generation, or via next.config.js for static policies. Use middleware if you need nonces for inline scripts.
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
const nonce = Buffer.from(
crypto.randomUUID()
).toString('base64');
const csp = [
"default-src 'self'",
`script-src 'self' 'nonce-${nonce}'`,
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"object-src 'none'",
"base-uri 'self'",
"frame-ancestors 'none'"
].join('; ');
const response = NextResponse.next();
response.headers.set(
'Content-Security-Policy', csp
);
response.headers.set('x-nonce', nonce);
return response;
}Laravel
Add CSP via middleware or use the spatie/laravel-csp package for a structured approach.
// app/Http/Middleware/CspHeader.php
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set(
'Content-Security-Policy',
"default-src 'self'; "
. "script-src 'self'; "
. "object-src 'none'; "
. "frame-ancestors 'none'"
);
return $response;
}Django
Use django-csp for declarative CSP or set headers in custom middleware.
# pip install django-csp
# settings.py
MIDDLEWARE = [
'csp.middleware.CSPMiddleware',
# ...
]
CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'",)
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'")
CSP_IMG_SRC = ("'self'", "data:")
CSP_OBJECT_SRC = ("'none'",)
CSP_FRAME_ANCESTORS = ("'none'",)
CSP_BASE_URI = ("'self'",)Ruby on Rails
Rails has built-in CSP support via the content_security_policy initializer.
# config/initializers/content_security_policy.rb
Rails.application.configure do
config.content_security_policy do |policy|
policy.default_src :self
policy.script_src :self
policy.style_src :self, :unsafe_inline
policy.img_src :self, :data
policy.object_src :none
policy.frame_ancestors :none
policy.base_uri :self
end
endCloudflare Workers
Add CSP at the edge for any origin behind Cloudflare.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const response = await fetch(request);
const newResponse = new Response(
response.body, response
);
newResponse.headers.set(
'Content-Security-Policy',
"default-src 'self'; "
+ "script-src 'self'; "
+ "object-src 'none'"
);
return newResponse;
}Frequently asked questions
What is a Content-Security-Policy header?+
Content-Security-Policy (CSP) is an HTTP response header that tells the browser which sources are allowed to load resources like scripts, styles, images, and fonts. It acts as an allowlist. Anything not explicitly permitted is blocked. CSP is the single most effective defense against Cross-Site Scripting (XSS) attacks. Full guide: What is CSP
How does CSP prevent XSS attacks?+
XSS attacks work by injecting malicious scripts into your page. CSP blocks these scripts because the attacker's origin is not in your allowlist. Even if an attacker manages to inject a script tag, the browser refuses to execute it because the source violates the policy. This makes CSP a critical layer of defense beyond input sanitization.
What does 'unsafe-inline' mean and should I use it?+
'unsafe-inline' allows execution of inline script tags and inline event handlers (onclick, onerror, etc.). This significantly weakens CSP because attackers who can inject HTML can also inject inline scripts. Avoid it for script-src whenever possible. Use nonces or hashes instead. For style-src, 'unsafe-inline' is more common because many CSS frameworks rely on inline styles.
What is the difference between CSP and X-Frame-Options?+
X-Frame-Options only controls whether your page can be framed (embedded in an iframe). CSP's frame-ancestors directive does the same thing but with more flexibility. You can allow specific origins instead of just DENY or SAMEORIGIN. CSP also covers scripts, styles, images, fonts, connections, and many other resource types. Use both for maximum browser compatibility.
How do I test CSP without breaking my site?+
Use Content-Security-Policy-Report-Only instead of Content-Security-Policy. This tells the browser to report violations without actually blocking anything. Add a report-uri or report-to directive to collect violation reports. Monitor the reports, fix any legitimate resources that get flagged, then switch to enforcing mode.
Why does my site break after adding CSP?+
CSP blocks any resource not explicitly allowed. Common causes: inline scripts or styles (need 'unsafe-inline' or nonces), third-party analytics scripts (add their domain to script-src), Google Fonts (add fonts.googleapis.com to style-src and fonts.gstatic.com to font-src), CDN-hosted libraries (add the CDN domain to script-src). Start with Report-Only mode to identify what needs to be allowed.
What is a CSP nonce and how do I use it?+
A nonce is a random, single-use token generated on each page load. You add it to your CSP header (script-src 'nonce-abc123') and to each inline script tag. The browser only executes scripts with a matching nonce. This is safer than 'unsafe-inline' because an attacker cannot guess the nonce. Your server must generate a new nonce for every response.
Do I need CSP if I already sanitize user input?+
Yes. Input sanitization is important but not foolproof. Bypasses are discovered regularly. CSP is a defense-in-depth layer. Even if sanitization fails and an attacker injects a script, CSP blocks it from executing. Think of CSP as your seatbelt: you still drive carefully, but the seatbelt saves you when something goes wrong.
Which CSP directives should I always set?+
At minimum: default-src 'self' (baseline), script-src 'self' (block injected scripts), object-src 'none' (block plugins), base-uri 'self' (prevent base tag hijacking), and frame-ancestors 'none' (prevent clickjacking). These five directives block the most common attack vectors with minimal compatibility impact.
How do I add CSP to my Next.js or Vercel project?+
In Next.js, add a headers() function in next.config.js or use middleware. For Vercel, add a headers array in vercel.json. You can also set CSP in a custom middleware.ts file for dynamic nonce generation. Our generator provides copy-paste code for both approaches.
Related resources
Test your CSP on a live site
Use our header checker to verify your CSP is deployed correctly, or run a full scan covering 150+ security checks.
Run Full Security ScanClaude AI helped me with phrasing and proofreading in this article.