csrf token in ajax laravel

To handle CSRF tokens in AJAX requests within a Laravel application, the token needs to be included in the request. Laravel’s built-in VerifyCsrfToken middleware automatically validates this token.

1. Include the CSRF token in a meta tag:

Add a meta tag in your Blade layout to make the CSRF token accessible to your JavaScript:

Code

<meta name="csrf-token" content="{{ csrf_token() }}">

2. Configure AJAX requests to include the token:

a. Using jQuery:

You can configure jQuery’s ajaxSetup to automatically include the CSRF token in the headers of all subsequent AJAX requests:

JavaScript

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

b. Manually for specific AJAX calls:

Alternatively, you can manually include the token in the data or headers of individual AJAX requests:

JavaScript

$.ajax({
url: '/your-endpoint',
type: 'POST',
data: {
_token: $('meta[name="csrf-token"]').attr('content'),
// other data
},
// or in headers:
// headers: {
// 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
// },
success: function(response) {
// handle success
},
error: function(error) {
// handle error
}
});

c. Using Axios (or other JavaScript frameworks):

Similar to jQuery, you can configure Axios to include the token in the request headers:

JavaScript

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

Explanation:

  • Laravel’s csrf_token() helper generates a unique token for each user session.
  • By embedding this token in a meta tag, JavaScript can access it.
  • Including the token in the X-CSRF-TOKEN header (or as _token in the request body for form-like submissions) allows Laravel’s VerifyCsrfToken middleware to validate the request, ensuring it originates from a legitimate source and preventing Cross-Site Request Forgery attacks.



Leave a Reply