React to Laravel CSRF token mismatch

51 Views Asked by At

So I've tried a lot of solution online but none had work, I always get 419 error when sending a post request from react to laravel.

cors.php

    'paths' => ['*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

method for fetching CSRF Token

  const csrf = () => axios.get('http://localhost:8000/sanctum/csrf-cookie', {
    withCredentials: true,
  } ).then((res) => console.log(res))

post request

 await csrf();
    axios.post(`http://localhost:8000/login`, payload, {
      headers: {
        "Content-Type": 'application/json',
        "X-XSRF-TOKEN": document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*=\s*([^;]*).*$)|^.*$/, '$1'),
      },
      withCredentials: true,
      withXSRFToken: true,
      
    })

I've checked if the token sent in the header is the same but I still get CSRF token mismatch as you can see here, the cookies are the same on the request header: Browser Cookies

CSRF token on request header

1

There are 1 best solutions below

0
Erik Roznbeker On

In my experience, when react SPA and laravel are on different domains this combination works:

  • set SANCTUM_STATEFUL_DOMAINS in laravel .env
  • make your own api/login route

You can check this example: https://github.com/erikroznbeker/sanctum-laravel-csrf