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

agodoo's avatar
Level 2

CSRF issue consuming Laravel API from NUXT 3 application

Hello, I'm trying to consume a Laravel API from a NUXT application using useFectch but I'm getting a "CSRF token mismatch" error.

Starting from the beginning...

I wrote my Laravel API that is intended to check user login and reply with a sanctum token. this is my route inside api.php

Route::controller(RegisterController::class)->group(function(){ Route::post('login', 'login'); }); the controller method accept as input parameters email and password

if I call myapi this way from Postman, setting the 2 parameters in the body this way { "email": "[email protected]", "password": "qdIekoUx" }

https://myapi.it/api/login

it works perfectly sending me the Sanctum token that I will use in the next calls.

Instead if I call the same API from my javascript app (NUXT 3) thisway const reqData = { "email": "[email protected]", "password": "qdIekoUx" } const { data, error } = await useFetch('https://myapi.it/api/login', { method: 'POST', body: reqData }) console.log(data)

it replies with "CSRF token mismatch"; I don't understand why! If I understood well Laravel API routes do not perform a CSRF validation...

Anyone can help me?

0 likes
3 replies
agodoo's avatar
Level 2

@GdS thank you. I tried adding your code to my request:

const reqData = { "email": "[email protected]", "password": "qdIekoUx" }
const { data, error } = await useFetch('https://myapy.it/api/login', {
    method: 'POST',
    body: reqData,
    headers: {
        accept: "application/json",
    },
    credentials: "include"
})

In this way I get this error: "Cross OPrigin Resource Sharing error: PreflightWildcardOriginNotAllowed"

My sanctum configuration in config/sanctum: 'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( '%s%s', '127.0.0.1,127.0.0.1:8000,::1', Sanctum::currentApplicationUrlWithPort() ))),

my CORS configuration in Laravel is: 'paths' => ['api/', 'sanctum/csrf-cookie'], 'allowed_methods' => [''], 'allowed_origins' => [''], 'allowed_origins_patterns' => [], 'allowed_headers' => [''], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false,

My NUXT app is actually running locally at http://localhost:3000/

GdS's avatar

@agodoo Thanks for sharing the code, it looks like cors.php is missing 'supports_credentials' => true and the default 'allowed_origins' => ['*'] (to be restricted in prod)

Please or to participate in this conversation.