Vue.js, Axios, Laravel X-CSRF-TOKEN, X-XSRF-TOKEN CSRF Protection

Image title

Simply generate a token using csrf_token() method and assign it in the global window object, in the main blade template file where you mount your vue.js application,

<script type="text/javascript">      
  window.csrf_token = "{{ csrf_token() }}"

import the axios library to your route file or store file in vue.js application,

import axios from 'axios';

add the following headers right bellow the axios import statement , 

axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN': window.csrf_token

Vue.js Laravel CSRF Token verification

we do not need to manually verify the CSRF token in ajax request,  The VerifyCsrfToken middleware, which is included in the web middleware group will check for the X-CSRF-TOKEN request header automatically for us


Laravel also stores the CSRF token in a XSRF-TOKEN cookie. You can use the cookie value to set the X-XSRF-TOKEN request header. Some JavaScript frameworks, do this automatically for you. It is unlikely that you will need to use this value manually.

Written by Akram Wahid 4 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in


Be the first one to write a response :(

{{ }} - {{ item.created_at_human_readable }}

{{ }} - {{ reply.created_at_human_readable }}