How to include csrf token in an external js file in Laravel

How to include csrf_token() in an external js file in Laravel?

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application. Since this token is stored in the user's session and changes each time the session is regenerated, a malicious application is unable to access it.

The current session's CSRF token can be accessed via the request's session or via the csrf_token helper function:

example : 

use Illuminate\Http\Request;
 
Route::get('/token', function (Request $request) {
    $token = $request->session()->token();
 
    $token = csrf_token();
 
    // ...
});

Anytime you define a "POST", "PUT", "PATCH", or "DELETE" HTML form in your application, you should include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the request.

What should I do if I want to external js files with Laravel ?. You can definitely copy the code below if you want to use crsf-token in external javascript file.

1. add <meta> tag with the token to the blade layout:

<meta name="_token" content="{{ csrf_token() }}">

2. setup ajax requests:

$(function() {
  $.ajaxSetup({
    headers: {
      'X-CSRF-Token': $('meta[name="_token"]').attr('content')
    }
  });
});

A few articles about How to include csrf_token() in an external js file in Laravel?. Hopefully this article is useful for you. Thanks.


Previous Post Next Post