Csrf token in vue component

Csrf token in vue component

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Retrieving CSRF Tokens in Vue Components with Laravel

When integrating Vue.js into a Laravel application, you quickly run into the reality that client-side JavaScript cannot directly access PHP variables like $csrf_token. Your current setup correctly intercepts requests using Vue.http.interceptors to attach MyApp.csrfToken to every outgoing request. However, this approach has a fundamental limitation: it protects API calls and AJAX submissions but does not help when you need to render the token inside a standard HTML <form> tag within a Vue component's template.

The line {!! csrf_field() !!} in your Vue component's template is attempting to execute Blade directives. This works perfectly if the file is compiled by Laravel before being served to the browser. However, if that same component is loaded dynamically via an API response or if you are trying to access the token purely from JavaScript within the component logic, the token simply isn't available there.

The Problem with Direct Import Attempts

You asked whether it is possible to import MyApp.csrfToken directly into your template. The short answer is no, not in the way you might expect. The @csrf directive (or {!! csrf_field() !!}) relies on Laravel's Blade engine to generate the hidden input field. Once the Blade compiler has run and sent the HTML to the browser, the token exists only as a string of characters within that specific DOM element. JavaScript running inside the component cannot "import" a variable from a different PHP execution context because they are distinct layers.

If you attempt to use {{ MyApp.csrfToken }} in your template, it will output the raw JavaScript variable name or an empty string, rather than the actual token value. The token is not stored as a global JavaScript constant that Vue components can easily reference for static rendering purposes.

The Dynamic Injection Solution

To solve this, you must leverage Laravel's mix() function or the Vite build process to inject the token at compile time. This ensures the token is available in your HTML before it even reaches the browser.

In your resources/js/bootstrap.js, after setting up your interceptors, you can append a meta tag that contains the token:

// resources/js/bootstrap.js
document.head.insertAdjacentHTML(
  'beforeend',
  `<meta name="csrf-token" content="${MyApp.csrfToken}">`
);

This approach is robust because it runs every time the application bundle is built or cached. When your Vue component renders, you can simply query that meta tag to get the current token value for any form submission:

<!-- In your Vue component template -->
<div class="modal fade">
    <form @submit.prevent="submitForm" method="POST" action="/">
        <!-- Retrieve token from DOM -->
        <input type="hidden" name="_token" :value="csrfToken">
        
        <!-- Your form fields -->
        <input type="text" name="data" value="test">
        
        <button type="submit">Submit</button>
    </form>
</div>

<script>
export default {
    computed: {
        csrfToken() {
            return document.querySelector('meta[name="csrf-token"]').content;
        }
    },
    methods: {
        submitForm(e) {
            console.log('Submitting form with token:', this.csrfToken);
        }
    }
};
</script>

Why This Works Better Than Interceptors for Forms

Your existing interceptor logic handles axios requests beautifully. It attaches the header to every request made via your HTTP client. However, a standard <form> tag submits data directly to the server without going through your Vue HTTP client instance unless you explicitly intercept it with an event listener or use a custom submit handler that sends data via fetch or axios.

By injecting the meta tag and accessing it in the computed property, you ensure that even if you have legacy forms or third-party scripts submitting to your Laravel routes, they carry the correct CSRF token. This hybrid approach maintains your existing security headers for API calls while providing a reliable source for static form submissions.

Trade-offs and Best Practices

The primary trade-off here is reliance on the DOM for the token value. If you were rendering these components in an environment without a full browser context (like certain Node.js server-side render setups), querying document.querySelector would fail. For standard Laravel + Vue setups where the frontend runs entirely in the browser, this is negligible overhead.

Always ensure that your build step (npm run dev or npm run prod) includes the injection logic. If you use caching, remember that MyApp.csrfToken might change between deployments, so you must invalidate your assets cache to prevent old tokens from being used with new server sessions.

Our network