Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maya-k-andersen's avatar

React + Laravel + Sanctum for api token authentication(NOT cookie)

I am trying to get React and Laravel to work together using the middleware Sanctum.

I can read many examples of people trying to do this with a cookie based setup, but I am trying to use the token setup for a pure API approach. I am doing this because I want to prepare the backend for use in a mobile app where cookies are not available.

This is a part of my setup:

/backend/routes/api.php:

Route::post('/getAccessToken', [ UserController::class, 'getAccessToken'] );

/frontend/store/api.js

static login( user ) {

    var formData = new FormData();
    formData.append('username', user.username);
    formData.append('password', user.password )
    formData.append('deviceName', 'browser');

    return fetch( 
        'http://localhost:5001/api/getAccessToken, {
            method : 'post',
            body : formData
        }
    );
}

My problems is that it forces a CSRF token check, when the login route is accessed. That is even if the login route shouldn't be guarded by Sanctum. This of course fails when I am logging in and don't yet have a token to attach to the request. As I understand the token is only needed on accessing guarded routes after login. I have double checked that it is accessing the right route by renaming it to something fake and getting an error.

Am I doing something wrong with the use of Sanctum or is Sanctum just not the preferred use for api tokens? Should I maybe look into JWT instead?

Thank you in advance for your help. <3

0 likes
1 reply
maya-k-andersen's avatar

I solved it myself:

In:

/backend/app/Http/Kernel.php

I had added:

\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,

It worked when I removed that line. I had failed to understand that a SPA equals the use of cookies, because I would say that I am also working on a SPA that just uses API tokens instead.

Please or to participate in this conversation.