Weave Code
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 Package

spatie/laravel-csp

Add Content Security Policy (CSP) headers to your Laravel app with easy configuration and preset policies. Control which scripts, styles, images, and connections are allowed, reduce XSS/data exfiltration risk, and support reporting and nonces.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/laravel-csp
    php artisan vendor:publish --tag=csp-config
    

    This publishes the config/csp.php file with sensible defaults.

  2. Enable CSP Globally: Register the middleware in bootstrap/app.php:

    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(\Spatie\Csp\AddCspHeaders::class);
    })
    
  3. First Use Case: Start with the Basic preset (already included in the config). This allows scripts, styles, images, and other resources from your own domain and common CDNs.

    // config/csp.php
    'presets' => [
        Spatie\Csp\Presets\Basic::class,
    ],
    
  4. Verify CSP Headers: Check the response headers in your browser's DevTools (Network tab) or via curl -I http://your-app.test. You should see headers like:

    Content-Security-Policy: script-src 'self' 'unsafe-inline'; ...
    

Implementation Patterns

Core Workflows

  1. Preset-Based Configuration: Use built-in presets for common services (e.g., Google Analytics, Stripe, Hotjar). Add them to the presets array in config/csp.php:

    'presets' => [
        Spatie\Csp\Presets\Basic::class,
        Spatie\Csp\Presets\Google::class, // For Google Analytics/Tag Manager
        Spatie\Csp\Presets\Stripe::class,
    ],
    
  2. Route/Group-Level Overrides: Override presets for specific routes or groups:

    Route::middleware([
        \Spatie\Csp\AddCspHeaders::class . ':' . \Spatie\Csp\Presets\Basic::class,
    ])->group(function () {
        // Routes with Basic CSP
    });
    
    Route::get('/admin', \App\Http\Controllers\AdminController::class)
        ->middleware(\Spatie\Csp\AddCspHeaders::class . ':' . \Spatie\Csp\Presets\Stripe::class);
    
  3. Dynamic Directives: Add global directives (e.g., allow unsafe-inline for development):

    'directives' => [
        [\Spatie\Csp\Directive::SCRIPT, \Spatie\Csp\Keyword::UNSAFE_INLINE],
    ],
    
  4. Nonce Handling for Inline Scripts/Styles: Use nonces for inline scripts/styles to avoid unsafe-inline:

    <script nonce="{{ csp_nonce() }}">
        // Inline script
    </script>
    

    Ensure nonce_enabled is true in config/csp.php.

  5. Report-Only Mode: Test CSP changes without breaking production:

    'report_only_presets' => [
        Spatie\Csp\Presets\Basic::class,
    ],
    

    Configure a reporting endpoint (e.g., Report URI):

    'report_uri' => env('CSP_REPORT_URI', 'https://your-report-uri.com/csp-report'),
    
  6. Blade Integration: Add CSP meta tags to HTML responses:

    <head>
        @cspMetaTag
    </head>
    

Integration Tips

  1. Vite/Laravel Mix: Disable CSP during hot reloading (add to config/csp.php):

    'enabled_while_hot_reloading' => env('CSP_ENABLED_WHILE_HOT_RELOADING', true),
    
  2. Custom Presets: Create a preset for third-party services not included in the package:

    namespace App\Csp;
    
    use Spatie\Csp\Preset;
    
    class CustomServicePreset extends Preset
    {
        public function directives(): array
        {
            return [
                \Spatie\Csp\Directive::CONNECT_SRC => ['https://custom-service.com'],
                \Spatie\Csp\Directive::SCRIPT_SRC => ['https://custom-service.com'],
            ];
        }
    }
    

    Register it in config/csp.php:

    'presets' => [
        \App\Csp\CustomServicePreset::class,
    ],
    
  3. Environment-Specific Config: Use environment variables to toggle CSP:

    'enabled' => env('CSP_ENABLED', false), // Disable in staging
    
  4. Debugging CSP: Use report-only mode to log violations before enforcing:

    'report_only_presets' => [\Spatie\Csp\Presets\Basic::class],
    'report_only_uri' => env('CSP_REPORT_ONLY_URI'),
    

Gotchas and Tips

Pitfalls

  1. Broken Resources:

    • Issue: CSP blocks scripts/styles from unexpected sources (e.g., third-party widgets).
    • Fix: Add the missing domain to the relevant directive (e.g., script-src or connect-src). Use report-only mode to identify violations first.
  2. Nonce Mismatches:

    • Issue: Inline scripts/styles fail with Refused to execute inline script if the nonce doesn’t match.
    • Fix: Ensure nonce_enabled is true and nonces are generated consistently. For Vite, use @vite('resources/js/app.js') with nonces:
      <script nonce="{{ csp_nonce() }}">
          @vite('resources/js/app.js')
      </script>
      
  3. Hot Reloading Conflicts:

    • Issue: CSP blocks Vite/Laravel Mix hot reloading if not configured.
    • Fix: Set 'enabled_while_hot_reloading' => true in config/csp.php.
  4. Reporting Endpoint Misconfiguration:

    • Issue: CSP violations aren’t logged if report_uri is misconfigured.
    • Fix: Verify the endpoint URL and ensure it’s accessible. Use a service like Report URI for testing.
  5. Overly Restrictive Policies:

    • Issue: Blocking unsafe-inline or unsafe-eval breaks legacy code.
    • Fix: Use nonces for inline scripts or temporarily allow unsafe-inline in development:
      'directives' => [
          [\Spatie\Csp\Directive::SCRIPT, \Spatie\Csp\Keyword::UNSAFE_INLINE],
      ],
      
  6. Caching Headers:

    • Issue: CSP headers are cached by browsers/CDNs, delaying policy updates.
    • Fix: Use Cache-Control: no-cache for CSP headers or increment the policy hash (e.g., append a version query string).

Debugging Tips

  1. Check Headers: Use curl -I http://your-app.test or browser DevTools (Network tab) to verify CSP headers are applied.

  2. Test in Report-Only Mode: Enable report_only_presets and monitor violations before enforcing:

    'report_only_presets' => [\Spatie\Csp\Presets\Basic::class],
    'report_only_uri' => 'https://your-report-uri.com/csp-report',
    
  3. Browser Console: Look for CSP violation messages in the Console tab (e.g., Refused to load the script).

  4. Log Violations: Use a logging service (e.g., Sentry, Laravel Log) to process CSP reports:

    // config/csp.php
    'report_uri' => 'https://your-app.test/csp-report',
    

    Create a route to handle reports:

    Route::post('/csp-report', [\App\Http\Controllers\CspReportController::class, 'store']);
    
  5. Validate Directives: Use the CSP Evaluator to test your policy.


Extension Points

  1. Custom Nonce Generator: Override the default nonce generator for custom logic:

    // config/csp.php
    'nonce_generator' => \App\Services\CustomNonceGenerator::class,
    
  2. Dynamic Presets: Load presets dynamically based on user roles or environments:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        if (app()->environment('production')) {
            config(['csp.presets' => [
                \Spatie\Csp\Presets\Basic::class,
                \Spatie\Csp\Presets\Google::class,
            ]]);
        }
    }
    
  3. Middleware Logic: Extend AddCspHeaders to conditionally apply CSP:

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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai