Cross-Site Request Forgery (CSRF) protection is crucial for securing web applications. In a typical setup with ReactJS as the frontend and Laravel as the backend, you can follow these steps to handle CSRF protection:
Verify CSRF Token in Laravel:
Laravel provides a built-in CSRF protection mechanism. Ensure that the VerifyCsrfToken
middleware is applied to your routes.
php// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
// Add any routes that should be excluded from CSRF protection here
];
Make sure that your API routes are not included in the CSRF protection.
Include CSRF Token in Responses:
When rendering the initial HTML page, include the CSRF token in the meta tag. Laravel provides the csrf_token()
function for this purpose.
blade<meta name="csrf-token" content="{{ csrf_token() }}">
Set Up Axios or Fetch:
If you are using Axios for HTTP requests, you can set up a global default header for the CSRF token. If you're using fetch
, you can include the token in the headers manually.
javascript// Using Axios
import axios from 'axios';
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').content;
// Using Fetch
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
const headers = {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken,
};
Handle CSRF Token in Requests: Include the CSRF token in the headers of every request made from your React application.
javascript// Example using Axios
axios.post('/api/your-endpoint', data)
.then(response => {
// Handle response
})
.catch(error => {
// Handle error
});
Consider Using Axios Interceptors: You can use Axios interceptors to automatically inject the CSRF token into every request.
javascript// Add this in your setup file or main component
axios.interceptors.request.use((config) => {
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
config.headers['X-CSRF-TOKEN'] = csrfToken;
return config;
});
Test the Setup: Test your setup by making requests from your React application and ensuring that Laravel is not blocking them due to CSRF protection.
By following these steps, you can ensure that your ReactJS application is properly handling CSRF protection when communicating with a Laravel backend. Always make sure to keep your dependencies and libraries up to date to benefit from security patches and improvements.