Home / Snippets / Set up CSRF Token in Alpine.js within Laravel Application
Set up CSRF Token in Alpine.js within Laravel Application cover

Set up CSRF Token in Alpine.js within Laravel Application

2.2K

2 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this