Certainly! Here’s a step-by-step solution to help you implement Content Security Policy (CSP) headers for Cloudflare Turnstile in your Laravel + Inertia app using Spatie's laravel-csp package.
1. Ensure Middleware Is Registered Correctly
For Laravel (not Lumen), middleware should be registered in app/Http/Kernel.php, not in bootstrap/app.php. Make sure you add the CSP middleware to the global middleware stack or to the specific routes you want.
In app/Http/Kernel.php:
protected $middleware = [
// ...
\Spatie\Csp\AddCspHeaders::class,
];
Or, if you want it only on certain routes, add it to $middlewareGroups or use route middleware.
2. Use the Cloudflare Turnstile Preset
Spatie provides a preset for Cloudflare Turnstile. In your AppServiceProvider or a dedicated service provider, you can set the CSP policy:
use Spatie\Csp\Csp;
use Spatie\Csp\Directive;
use Spatie\Csp\Policies\CloudflareTurnstile;
public function boot()
{
Csp::extend('cloudflare-turnstile', CloudflareTurnstile::class);
// Optionally, you can customize further:
// Csp::extend('custom', function () {
// return (new CloudflareTurnstile())
// ->addDirective(Directive::SCRIPT, 'https://your-additional-domain.com');
// });
}
Then, in your config/csp.php:
return [
'policy' => Spatie\Csp\Policies\CloudflareTurnstile::class,
];
3. Clear Config Cache
After making changes, clear your config cache:
php artisan config:clear
4. Verify CSP Headers
- Open your browser’s dev tools.
- Go to the Network tab.
- Reload a page that should have the CSP header.
- Click on the document (usually the first request).
- Check the Headers section for
content-security-policy.
If you still don’t see the CSP header:
- Ensure your middleware is not being skipped (e.g., by a proxy, or by being registered in the wrong place).
- Make sure you’re not serving cached responses (try disabling any HTTP cache).
- If using Laravel Vapor or similar, ensure headers are not being stripped by your host/CDN.
5. Inertia.js & CSP
If you’re using Inertia.js with Vue/React, make sure your CSP allows the scripts/styles you need. The Turnstile preset should handle this, but you can always customize the policy as needed.
6. Debugging Tips
- Try adding a custom header in the same middleware to confirm it’s being applied.
- Check for typos in middleware registration.
- Ensure you’re not overriding the CSP header elsewhere in your app or server.
Summary:
- Register the middleware in
app/Http/Kernel.php. - Use the Cloudflare Turnstile preset.
- Clear config cache.
- Check headers in dev tools.
- Customize policy if needed.
Let me know if you need help with a specific step or error message!