Content Security Policy (CSP) Generator

Generate Content Security Policy headers with an interactive builder. Configure script-src, style-src, and all CSP directives with presets and custom domains.

Your data never leaves your browser

Enable directives above and configure their sources to generate a policy.

Enter a resource URL to check whether it would be allowed by the directives above.

How to Use

  1. Select a preset to start with a recommended baseline policy. The Strict preset blocks all sources except self-hosted resources, while the Moderate preset allows HTTPS and common patterns.
  2. Toggle individual directives on or off. Click the arrow button to expand a directive and configure its allowed sources.
  3. For each directive, check the keyword sources you need (such as 'self', 'unsafe-inline', or https:) and add custom domains like cdn.example.com or *.googleapis.com.
  4. The generated policy updates in real time below. Copy it as an HTTP header to add to your server configuration, or as an HTML meta tag to paste directly into your page's <head>.
  5. Use the Test section to paste a resource URL and see which directives would allow or block it.

What is Content Security Policy?

Content Security Policy (CSP) is a security standard introduced by the W3C that allows website operators to declare which sources of content are permitted to load on their pages. It is delivered via an HTTP response header (Content-Security-Policy) or an HTML <meta> tag. When a browser receives a CSP, it enforces the policy by blocking any resource that does not match the declared sources. This prevents a wide range of attacks, most notably cross-site scripting (XSS), where an attacker injects malicious scripts into a trusted page.

CSP was first implemented by Firefox 4 in 2011 and has since become a standard supported by all modern browsers. The current specification, CSP Level 3, adds features like 'strict-dynamic' for script propagation and the report-to directive for modern violation reporting. Major websites including Google, GitHub, Twitter, and Facebook all deploy CSP headers to protect their users.

Why CSP Matters for Web Security

Cross-site scripting remains one of the most common web vulnerabilities, consistently appearing in the OWASP Top 10. Traditional defenses like input validation and output encoding are essential but can miss edge cases. CSP provides a defense-in-depth layer: even if an attacker successfully injects a script tag into your HTML, the browser will refuse to execute it unless the source matches your policy. This dramatically reduces the impact of XSS vulnerabilities.

Beyond XSS prevention, CSP protects against several other attack vectors. The frame-ancestors directive prevents clickjacking by controlling who can embed your page in an iframe (replacing the older X-Frame-Options header). The form-action directive prevents form hijacking. The upgrade-insecure-requests directive helps migrate sites to HTTPS by automatically upgrading HTTP resource requests. Together, these directives form a comprehensive client-side security policy.

Common Directives Explained

  • default-src — The fallback directive. If a more specific directive (like script-src) is not set, the browser uses default-src instead. Set this to 'none' and explicitly configure each resource type for maximum security.
  • script-src — Controls JavaScript execution. This is the most important directive for XSS prevention. Avoid 'unsafe-inline' and 'unsafe-eval' when possible; prefer nonce-based or hash-based allowlisting.
  • style-src — Controls CSS loading and inline styles. While CSS injection is less dangerous than script injection, it can still be used for data exfiltration via CSS selectors.
  • img-src — Controls image sources. Remember to include data: if your application uses inline base64 images, and blob: for dynamically generated images.
  • connect-src — Controls fetch, XMLHttpRequest, WebSocket, and EventSource destinations. Critical for single-page applications that communicate with APIs.
  • object-src — Controls plugins like Flash. Should be set to 'none' on all modern sites since plugin-based content is obsolete.
  • frame-ancestors — Controls who can embed your page. Setting this to 'none' prevents all framing (equivalent to X-Frame-Options: DENY). Note: this directive cannot be used in meta tags.
  • base-uri — Restricts the <base> element, preventing attackers from changing the base URL to hijack relative links.

CSP Best Practices

Start with a restrictive policy and loosen it as needed, rather than starting permissive and trying to tighten it later. A solid starting point is: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'.

Use Content-Security-Policy-Report-Only during development to identify violations without breaking functionality. Set up a reporting endpoint to collect violations from real users. Services like report-uri.com and Sentry provide CSP violation aggregation and alerting.

Avoid 'unsafe-inline' for scripts whenever possible. Instead, use nonce-based CSP where your server generates a unique random nonce for each response and includes it in both the CSP header and each legitimate inline script tag. This allows your specific inline scripts to execute while blocking injected ones.

Review your CSP regularly as your application evolves. New third-party integrations (analytics, chat widgets, A/B testing tools) often require additional source entries. Automated CSP monitoring tools can alert you to violations that indicate either an attack or a misconfigured policy.

Debugging CSP Violations

When a resource is blocked by CSP, the browser logs a detailed error to the developer console. The error message includes the violated directive, the blocked URI, and the full policy. Open your browser's developer tools (F12), navigate to the Console tab, and look for messages starting with "Refused to load" or "Refused to execute."

Common issues include: inline scripts blocked by a missing 'unsafe-inline' or nonce (fix by adding a nonce, not by adding unsafe-inline), third-party scripts blocked because their domain is not in script-src (add the specific domain like https://www.googletagmanager.com), and eval() calls blocked because 'unsafe-eval' is not set (refactor the code to avoid eval, or add unsafe-eval as a last resort).

For production debugging, use the report-uri or report-to directives to send violation reports to a server endpoint. This captures violations from real users that you cannot reproduce in your own browser. Aggregate these reports to identify patterns and prioritize fixes.

CSP and Single-Page Applications

Single-page applications (SPAs) built with React, Vue, or Angular present specific CSP challenges. Many frameworks inject inline styles or use eval()-like patterns for template compilation. React's JSX does not use eval, but some older Angular patterns do. Webpack's default configuration injects scripts via eval in development mode — make sure your production build uses a CSP-compatible mode.

For SPAs, pay special attention to connect-src since all API calls must match this directive. If your app communicates with multiple backend services, list each API domain explicitly. WebSocket connections (wss://) also require matching connect-src entries.

Related Tools

Beautify your HTML pages with the HTML Beautifier. Generate SHA hashes for CSP integrity attributes with the Hash Generator. Look up HTTP status codes in the HTTP Status Code Reference. Convert cURL commands to code with the cURL Converter. Decode JSON Web Tokens with the JWT Decoder. Encode URLs safely with the URL Encoder.

Frequently Asked Questions

What is a Content Security Policy (CSP)?
A Content Security Policy is an HTTP response header that tells browsers which sources of content (scripts, styles, images, etc.) are allowed to load on your page. It is one of the most effective defenses against cross-site scripting (XSS) attacks because it prevents unauthorized scripts from executing, even if an attacker manages to inject HTML into your page.
What is the difference between the HTTP header and the meta tag?
Both deliver the same policy to the browser, but the HTTP header (Content-Security-Policy) supports all directives, while the HTML meta tag cannot use frame-ancestors, report-uri, or report-to. The HTTP header is preferred because it is applied before any HTML is parsed, and it supports reporting directives for monitoring violations.
Why does my site break after adding a CSP?
A CSP blocks any resource that does not match the allowed sources. Common causes include inline scripts or styles blocked because unsafe-inline is not set, third-party scripts (analytics, ads, chat widgets) not listed in script-src, fonts loaded from external CDNs not listed in font-src, or images from external domains not listed in img-src. Start with a report-only policy (Content-Security-Policy-Report-Only) to identify violations before enforcing.
What does default-src do?
default-src acts as a fallback for any directive that is not explicitly set. If you set default-src to 'self' and do not set script-src, the browser uses 'self' for script loading. It is best practice to set default-src to 'none' and then explicitly allow each resource type you need, following the principle of least privilege.
Should I use 'unsafe-inline' in my CSP?
Using 'unsafe-inline' significantly weakens your CSP because it allows any inline script or style to execute, which is exactly what XSS attacks exploit. Instead, use nonce-based ('nonce-...') or hash-based ('sha256-...') allowlisting for specific inline scripts. If you must use unsafe-inline for styles, combine it with other restrictions to limit exposure.
How do I monitor CSP violations without breaking my site?
Use the Content-Security-Policy-Report-Only header instead of Content-Security-Policy. This tells the browser to report violations without actually blocking resources. Set up a report-uri or report-to endpoint to collect violations, review the reports, adjust your policy, and then switch to enforcement mode once you are confident no legitimate resources are blocked.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 47 developer tools. One command: npx @codetidy/mcp

Drop file to load