Set CSRF/XSRF token with laravel + reactjs

Updated: Mar 03, 2025

Set CSRF/XSRF token with laravel + reactjs

To set Cross-Site Request Forgery (CSRF) and Cross-Site Request Forgery (XSRF) tokens in a Laravel application with ReactJS, you need to follow these steps:

  1. Enable CSRF protection in Laravel:

By default, Laravel comes with CSRF protection enabled. You don't need to do anything extra to enable it. However, you need to make sure that the CSRF token is sent with every request from the client-side.

  1. Generate a CSRF token in Laravel:

You can generate a CSRF token in Laravel using the csrf_token() helper function. This function returns the current CSRF token value, which you can use in your ReactJS application.

<html lang="en">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
  1. Send the CSRF token from ReactJS to Laravel:

When making a request from ReactJS to Laravel, you need to include the CSRF token in the request headers. You can do this by creating an axios instance with the CSRF token as a default header.

import axios from 'axios';

const api = axios.create({
    baseURL: 'http://localhost:8000/api',
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
    }
});
  1. Verify the CSRF token in Laravel:

In Laravel, you can verify the CSRF token using the VerifyCsrfToken middleware. By default, this middleware is installed in the app/Http/Kernel.php file.

protected $middlewareGroups = [
    'web' => [
        // ...
        \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
    ],

    // ...
];
  1. Handle CSRF token errors in ReactJS:

If a request from ReactJS to Laravel fails due to a missing or invalid CSRF token, Laravel will return a 419 status code. You can handle this error in ReactJS by using a catch block in your axios request.

api.interceptors.response.use(
    response => response,
    error => {
        if (error.response && error.response.status === 419) {
            // Handle CSRF token error
        }
        return Promise.reject(error);
    }
);

By following these steps, you can set and verify CSRF/XSRF tokens in a Laravel application with ReactJS.