spatie/laravel-csp
Easily add Content Security Policy (CSP) headers to your Laravel app. Define and enforce CSP directives, report violations, and tighten what scripts, styles, and other resources can load or connect to—helping mitigate XSS and malicious third‑party code.
Start by installing the package via Composer: composer require spatie/laravel-csp. Next, publish the config with php artisan vendor:publish --tag=csp-config. The config file includes ready-to-use presets (like Basic, Google, Stripe) — pick the ones matching your dependencies. Register the AddCspHeaders middleware globally in bootstrap/app.php (Laravel 11+) or app/Http/Kernel.php (earlier versions). For immediate safe operation, enable report_only_presets first to test without breaking your app. Check the generated CSP header via browser devtools → Network tab to verify it’s applied.
Use presets for common services (e.g., add Google::class to presets for Google Analytics). For custom policies, extend Spatie\Csp\Preset and implement configure(Policy $policy), then register it in config/csp.php. Combine presets with global directives in config (e.g., add UNSAFE_INLINE for legacy inline styles in report_only_directives). Apply middleware per-route when you need per-frontend-view policies (e.g., ->middleware(AddCspHeaders::class . ':' . AdminPanel::class)). For Blade templates, use @cspMetaTag in <head> if your app uses CSP via meta tags instead of headers (e.g., for some embedded contexts). In Vite dev mode, set enabled_while_hot_reloading to true only after verifying hot reload works under CSP.
⚠️ CSP directives like script-src block inline scripts by default — enable nonce_enabled (default true) to let Blade auto-embed nonces in <script> tags, and use @vite('resources/js/app.js') which is nonce-aware. When moving from dev to prod, ensure your report_uri (e.g., Report URI, CSP Eater) is set up before enforcing policies to avoid blind deployment. The config’s directives array accepts tuples like [[Directive::SCRIPT, Directive::STYLE], [Keyword::SELF]] to DRY up repeated values — but avoid overuse for readability. Debug CSP violations by temporarily enabling report_only_presets and checking the browser console or report-uri logs — violations show exactly which resource was blocked. Note: CSP nonces change per request — never cache HTML containing nonces with a long Cache-Control. Finally, if your app uses_iframe-based third-party widgets (e.g., YouTube), remember to include frame-src 'self' https://www.youtube.com in your policy.
How can I help you explore Laravel packages today?