Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message
Laravel Csp

Laravel Csp Laravel Package

spatie/laravel-csp

Spatie's Laravel CSP package makes it easy to set Content Security Policy headers in Laravel apps with configurable policies and directives. It helps restrict which sites scripts can contact, reducing risks from malicious or compromised JavaScript dependencies.

View on GitHub
Deep Wiki
Context7

spatie/laravel-csp makes it easy to add Content Security Policy headers to your Laravel application, protecting users from cross-site scripting and data exfiltration by untrusted scripts. Instead of assembling header strings by hand, you define policies in PHP and let the package handle injection automatically.

  • Define policies as simple, testable PHP classes
  • Per-request policy selection via a Policy contract
  • Nonce generation for inline scripts and styles
  • Report-only mode and violation reporting support
  • Automatic header injection through middleware
Frequently asked questions about Laravel Csp
How do I install spatie/laravel-csp in a Laravel application?
Install it with composer require spatie/laravel-csp, then publish the config file so config/csp.php exists in your project. Register the AddCspHeaders middleware in bootstrap/app.php, either globally or only on the routes that need a policy. There are no migrations, queues, or database tables, so setup is limited to Composer, config, and one middleware registration. After that you can start in report-only mode while you author your directives.
Which Laravel versions does spatie/laravel-csp support?
The package is maintained by Spatie and tracks current Laravel releases, but version constraints change between releases. Check the require section on Packagist and the CHANGELOG before committing, especially if you are on an older or LTS Laravel version. Pin the package release whose constraints still list your framework version, and verify the current release cadence rather than relying on download or dependent counts.
How do I configure CSP directives and presets with spatie/laravel-csp?
Policy lives in config/csp.php, which exposes presets, directives, report_only_presets, and report_only_directives. Presets are named bundles of vendor allowlists, covering roughly 40 services such as Google Tag Manager, Stripe, HubSpot, Sentry, and Cloudflare Turnstile, so you enable a service instead of hand-writing domains. Directives let you add or override individual rules like script-src, img-src, or frame-ancestors. Because the policy is a versioned config file, it can be reviewed and audited like any other code change.
Can I use report-only mode to test CSP before enforcing it?
Yes, report-only is a first-class feature with separate report_only_presets, report_only_directives, report_only_uri, and report_only_to or reporting_endpoints settings. The browser blocks nothing but sends violation reports, so you can collect a baseline of what would break. Move to enforcement only after the report stream is quiet across real traffic, including checkout and consent flows. This is the single most important de-risking capability and should gate the whole rollout.
How do I apply a different CSP policy per route or route group?
Pass a preset to the middleware with Laravel's standard parameter syntax, for example AddCspHeaders::class . ':' . MyPreset::class, on a route or route group. That lets an admin panel, a marketing site, and a checkout flow each get their own policy instead of one global header. Register the middleware globally only if a single baseline policy is acceptable for every response. Per-route presets are the feature that makes the package practical for apps with heterogeneous pages.
Does spatie/laravel-csp work with CDN or full-page response caching?
A per-response nonce conflicts with cached HTML: cached markup carries a stale nonce that the next response's header rejects, and a shared nonce is effectively public. If you use Cloudflare or Varnish page caching, spatie/laravel-responsecache, or static page generation, resolve the nonce strategy before enforcing CSP. Options include excluding HTML from caching, using hash-based policies for static scripts, or injecting nonces at the edge. Test this early, because it is the most common reason CSP breaks in production.
Why do my inline scripts, Alpine.js, or Livewire break when I enable CSP?
Nonces authorize script tags that carry the nonce attribute; they do not authorize inline event handlers like onclick or eval-style constructs. Alpine.js needs its CSP build, Livewire and inline GTM snippets need review, and Vite's dev-mode inline injection often trips the policy. Run in report-only mode first and fix each violation at the source rather than loosening script-src with unsafe-inline. The breakage is an ecosystem-fit issue, not a defect in the package.
How do I customize or replace the CSP nonce generator?
The nonce generator is a swappable class configured through the nonce_generator key in config/csp.php. Point it at your own implementation when you need deterministic nonces, nonces injected by an edge worker, or a different source of randomness. This is the main architectural escape hatch if your caching or deployment model changes. Keep the implementation small so the rest of the middleware stays untouched.
What happens if nginx or my CDN also sends a CSP header?
Browsers enforce the intersection of every CSP header they receive, so the strictest policy wins and the combination can block resources neither policy intended to block. Adopting spatie/laravel-csp without removing upstream CSP headers produces breakage that is hard to attribute to the right layer. Audit your web server, WAF, and CDN configuration and keep a single source of truth for the policy. Also monitor the env-driven CSP_ENABLED flag, since a well-meant fix during an incident can silently disable the control.
Should I use spatie/laravel-csp or write my own CSP middleware?
A hand-rolled middleware is roughly 50 lines, so the plumbing is not where the value sits. The package's value is the preset catalog encoding vendor-published domain allowlists, plus report-only support, reporting endpoints, per-route presets, and a swappable nonce generator. If you only need a static header with no third-party services, rolling your own is reasonable. If you ship analytics, payments, and support widgets, the presets save days of error-prone research.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
vento/laravel-airbrake
wfeller/laravel-batch
maco-studios/mage-os-installer
busarm/armie
siberfx/laravel-logger
kfteam1991/dcat-admin
dashed/dashed-laposta
dashed/dashed-ecommerce-montaportal
dashed/dashed-ecommerce-etsy
neohq/string-blade-compiler
log1x/acf-composer
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core
nodisrupt/laravel-agent
sierratecnologia/media-manager