I am building a Laravel API connected to a NextJS SPA. I am using Sanctum session-based authentication.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'users' => [
'driver' => 'sanctum',
'provider' => 'users',
],
'admins' => [
'driver' => 'sanctum',
'provider' => 'admins',
]
]
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => Admin::class
]
],
In config/session.php 'encrypt' is set to true
These are my routes in routes/api.php
Route::get('/verify-admin-auth', [AdminController::class, 'verifyAuth']);
Route::post('/admin-login', [AdminController::class, 'authenticate']);
Route::middleware('auth:admins')->group(function () {
Route::get('/brands', [BrandController::class, 'index']);
Route::post('/brand', [BrandController::class, 'store']);
Route::get('/brand/{brand}', [BrandController::class, 'show']);
Route::put('/brand/{brand}', [BrandController::class, 'update']);
});
Now let's take an example where I delete all the cookies in my browser and access a protected route from the SPA. While accessing the route, it returns status code 401 as expected and my SPA is redirected to the login page but the response also sends a XSRF-Token cookie. Is that normal behavior, since I am not requesting the sanctum/csrf-cookie route?

Now after I login, these are the response cookies that I get:

My second question is why I keep getting XSRF-Token and laravel_session cookies with new values for every request? Shouldn't these values persist for every request?
As you can notice the Laravel response always sends 3 cookies for every request: XSRF-Token, laravel_session and one with a dynamic name. So, after every response, the XSRF-Token, laravel_session cookies' values are overwritten and a new cookie created for the one with the dynamic name. What this means is that the cookies with the dynamic names keeps adding up after every request and at some point there are too many cookies which leads to an error 431. Then I have to manually delete the cookies in my browser so I can continue using the system.
Is there a way to get rid of that issue?