I found a Way to Resolve the CSRF Token Mistach Error on Insomnia. By default we have a funcionality that takes a Header value and store it in a Tag/Environment Variable.
But the XSRF token comes with a bad formatation and just put it as reference on the headers is'nt enough to Correct it.
Below i'will pass a function that extract the corret value from the XSRF TOKEN in the header and store it correctly in a environment variable:
**1. Create an Empty envinronment variable**
```
{
"XSRF_TOKEN": ""
}
```
**2. Create a new HTTP Request on Insomnia, put your URL with GET method.**
````` you-api/sanctum/csrf-cookie` ``
**3. Below URL we have different paths of configuration like Params, Body, Auth, go to Scripts and put the code Below**
```
const cookieHeaders = insomnia.response.headers
.filter(h => h.key.toLowerCase() === 'set-cookie');
const xsrfHeader = cookieHeaders
.find(h => h.value.startsWith('XSRF-'));
console.log(xsrfHeader);
if (xsrfHeader) {
// 3. Extrai o valor do cookie
let xsrfValue = xsrfHeader.value
.split(';')\[0\] // "XSRF-TOKEN=âŠ"
.split('=')\[1\]; // pega sĂł o valor
xsrfValue = xsrfValue.slice(0, -3);
// 4. Armazena na base environment
insomnia.environment.set("XSRF_TOKEN", xsrfValue);
console.log('â XSRF-TOKEN salvo:', xsrfValue);
} else {
console.warn('â ïž XSRF-TOKEN nĂŁo encontrado no header');
}
```
In console of response you can see if any errors occurs.
**4. Finally put the variable on the Headers of any Http Request as you want. Like this:**
```
header value
X-XSRF-TOKEN {{XSRF_TOKEN}}
```
After that you will be able to make Your Request to your login and Have access to your application and Auth::user !
Obs: I already was receving the Token in Frontend so my Backend was okay, if you dont, just follow the steps of a lot of youtubers, in my case i've struggle for a while in this step because my domain of backend and frontend was not of the same origin.
i Create an environment domain for main application to redirect the localhost of Frontend and Backend.
My Backend is a server vagrant that points to **http://api-dev.local** and my frontend is
**http://frontend.api-dev.local**
Below my** vite.config.js** where i change the domain, "you have to point the domain in your hosts file of your system" i'm using Windows 11"
```
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
// server: {
// host: 'test-dev.local',
// port: 5173,
// https: false, // ou true se vocĂȘ gerar certificado local
// }
server: {
host: 'frontend.api-dev.local',
port: 5173,
https: false,
cors: true
}
})
```
and my Important Variables in **.env** of laravel
`APP_URL=http://api-dev.local
SESSION_DOMAIN=.api-dev.local
SANCTUM_STATEFUL_DOMAINS=http://frontend.api-dev.local:5173
FRONTEND_URL=http://frontend.api-dev.local:5173`
Final OBS:
The routes are in WEB not in API, below you see my **web.php** file
```
<?php
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;
use App\Modulos\Usuario\Http\ApiRoute as UsuarioRoute;
Route::get('/', function () {
return view('welcome');
});
Route::middleware('web')->group(function () {
Route::post('/login', \[AuthController::class, 'login'\])-\>name('login');
Route::post('/logout', \[AuthController::class, 'logout'\])-\>name('logout');
Route::get('/user', \[AuthController::class, 'user'\])-\>name('user')-\>middleware('auth');
UsuarioRoute::routes();
});
```
I'm not using the user route in this case, just return the user data in login.
My English is so Bad, glad to Help!
Finally you will be able to Resolve the problem