Kritim Yantra
Apr 08, 2025
CSRF (Cross-Site Request Forgery) protection is a crucial security feature in Laravel. When making AJAX requests, you might encounter:
419 | CSRF Token Mismatch
This error occurs because Laravel requires a valid CSRF token for state-changing requests (POST, PUT, PATCH, DELETE). Here's how to properly handle CSRF tokens in Laravel 12 AJAX requests.
VerifyCsrfToken
middleware$.ajax({
url: '/your-route',
type: 'POST',
data: {
_token: '{{ csrf_token() }}',
// other data
},
success: function(response) {
// handle response
}
});
// Set up once in your layout
<meta name="csrf-token" content="{{ csrf_token() }}">
// Configure AJAX globally
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Now all AJAX requests will include the token
$.ajax({
url: '/your-route',
type: 'POST',
data: { /* your data */ },
success: function(response) {
// handle response
}
});
fetch('/your-route', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({ /* data */ })
})
.then(response => response.json())
.then(data => console.log(data));
// Intercept 419 errors globally
$(document).ajaxError(function(event, xhr) {
if (xhr.status === 419) {
alert('Session expired. Please refresh the page.');
location.reload();
}
});
Check browser DevTools → Network tab:
X-CSRF-TOKEN
_token
Ensure your .env
has proper session config:
SESSION_DRIVER=cookie
SESSION_DOMAIN=.yourdomain.com
SESSION_SECURE_COOKIE=true # for HTTPS
Solution: Refresh CSRF token after authentication:
// In your login success handler
$.get('/refresh-csrf').done(function() {
// Continue with next requests
});
// Laravel route
Route::get('/refresh-csrf', function() {
return response()->json(['token' => csrf_token()]);
});
Solution: Ensure API routes are in routes/api.php
(excluded from CSRF by default)
If using separate frontend:
// config/cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie'],
You've now learned:
✅ Why CSRF protection exists
✅ Multiple ways to include tokens in AJAX
✅ Advanced scenarios and solutions
✅ Debugging and testing techniques
📌 Still facing issues? Drop your specific scenario in the comments! 👇
Transform from beginner to Laravel expert with our personalized Coaching Class starting June 25, 2025. Limited enrollment ensures focused attention.
1-hour personalized coaching
Build portfolio applications
Industry-standard techniques
Interview prep & job guidance
Complete your application to secure your spot
Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google