Posts Learn Components Snippets Categories Tags Tools new About
/

Set up CSRF Token in Alpine.js within Laravel Application

Learn how to set up CSRF token in Alpine JS within Laravel Application

Created on Nov 18, 2021

19 views

Sometimes you might need to set up CSRF Token in the header when performing POST and PUT Ajax requests and in the case when using Alpine.js you can specify it within the fetch header itself.
<meta name="csrf-token" content="{{ csrf_token() }}" />

Alpine.js CSRF Token


The fetch method now should have the X-CSRF-TOKEN specified inside the headers and then get the content of the "csrf-token" meta tag. For this example imagine we are going to send a "post" data to the backend to save a new post, the content should contain the "title", "slug" and "body" like below.
<form x-data="{
  post: {
    title: '',
    slug: '',
    body: '',
  },
  submit() {
    fetch('/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name=csrf-token]').content
      },
      body: JSON.stringify(this.post)
    })
    .then((data) => console.log(data))
}">
Do note that if you are using Axios as the HTTP library then this won't be necessary since it's already set up inside the bootstrap.js.
/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)