While working with Vue 3 and Laravel APIs, a common issue you might encounter is the “CSRF Token Mismatch” error. This problem arises when Axios, a popular HTTP client for making requests, fails to send the necessary X-XSRF-TOKEN
in the request header. This article explains how to resolve this issue by intercepting requests and adding the required token.
Understanding the Problem
The Cross-Site Request Forgery (CSRF) Token Mismatch error typically occurs when a request is made from a local domain to a Laravel API. Laravel expects a CSRF token as a part of the request for security purposes. However, when Axios does not include this token in the header, Laravel rejects the request, leading to an error.
The Solution: Intercepting Requests with Axios
The solution lies in modifying the request before it’s sent. By using Axios’ request interceptors, you can ensure that the X-XSRF-TOKEN
is included in every request header. Below is a step-by-step guide on how to implement this.
1. Setting Up Axios Instance
First, create an Axios instance with the necessary configurations:
import axios from 'axios';
import Cookies from 'js-cookie';
const httpApi = axios.create({
baseURL: process.env.VUE_APP_API_URL,
withCredentials: true,
headers: {
"X-Requested-With": "XMLHttpRequest",
},
});
Here, withCredentials: true
is crucial for sending cookies in cross-origin requests.
2. Adding a Request Interceptor
Next, add a request interceptor to Axios:
httpApi.interceptors.request.use(function (config) {
const token = Cookies.get('XSRF-TOKEN');
if (token) {
config.headers['X-XSRF-TOKEN'] = token;
}
return config;
}, function (error) {
return Promise.reject(error);
});
This interceptor function runs before each request is sent. It retrieves the CSRF token from the cookies using js-cookie
and adds it to the request headers.
3. Exporting the Configured Axios Instance
Finally, export the configured Axios instance for use in your Vue components:
export { httpApi };
Conclusion
By intercepting requests and adding the X-XSRF-TOKEN
header, you can smoothly integrate Vue 3 with a Laravel API without encountering CSRF Token Mismatch errors. This approach enhances the security of your application while ensuring seamless communication between the client and server.