Navigation

Laravel

Fix: 419 CSRF Token Mismatch When Calling an API from JavaScript

Solve Laravel's 419 CSRF token error when making AJAX requests. Learn how to properly send CSRF tokens with JavaScript API calls.

Problem: Your JavaScript AJAX requests to Laravel return a 419 error saying "CSRF token mismatch" even though you're including the token.

Solution:

// Option 1: Include CSRF token in headers
// Add to your blade template
<meta name="csrf-token" content="{{ csrf_token() }}">

// JavaScript (Axios example)
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

// Or with fetch()
fetch('/api/endpoint', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
    },
    body: JSON.stringify(data)
});

// Option 2: Exclude API routes from CSRF (app/Http/Middleware/VerifyCsrfToken.php)
protected $except = [
    'api/*',
    'webhook/*'
];

// Option 3: Use Sanctum for SPA authentication (recommended)
// Routes in routes/api.php are automatically excluded from CSRF

Why it works: Laravel expects a CSRF token for all POST, PUT, PATCH, and DELETE requests. The token must be sent in the X-CSRF-TOKEN header or _token field. API routes (routes/api.php) bypass CSRF by default since they use token authentication.

Best practice: For SPAs, use Laravel Sanctum which handles CSRF protection automatically for same-domain requests.

Related Topics

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel