Table Of Contents
Problem
Your API routes or webhook endpoints are failing with 419 errors because Laravel's CSRF protection is blocking requests from external services.
Solution
Add route URIs to the $except
array in VerifyCsrfToken
middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*/
protected $except = [
'api/*',
'webhook/stripe',
'webhook/github',
'external-payment/callback',
];
}
For dynamic exclusions:
class VerifyCsrfToken extends Middleware
{
protected $except = [
// static routes
];
public function handle($request, Closure $next)
{
// Conditionally disable CSRF
if ($request->is('api/*') && $request->header('X-API-Key')) {
return $next($request);
}
return parent::handle($request, $next);
}
}
Why It Works
Laravel automatically includes CSRF protection for all POST, PUT, PATCH, and DELETE routes. The $except
array tells Laravel to skip CSRF verification for matching URIs. Use wildcards (*
) for pattern matching.
Best practices for API security without CSRF:
// Use API authentication instead
Route::middleware(['auth:sanctum'])->group(function () {
Route::post('/api/users', [UserController::class, 'store']);
});
// For webhooks, verify signatures
public function handleWebhook(Request $request)
{
$signature = $request->header('X-Webhook-Signature');
$payload = $request->getContent();
if (!$this->verifyWebhookSignature($payload, $signature)) {
abort(401);
}
// Process webhook...
}
Related: Laravel Collections: Beyond Basic Array Operations | Laravel Events and Listeners: Building Decoupled Applications | Laravel API Development: Best Practices and Security | PHP Security: Common Vulnerabilities and Prevention | API Authentication & Security 2025: Complete Guide
Add Comment
No comments yet. Be the first to comment!