By default #laravel Sanctum is using auth tokens to identify the API request, but how to use cookie-based authentification for API requests with Sanctum in Laravel 11?

But wait!
Why would i use cookie-based auth when Sanctum is built to use auth tokens?
Take a look at this video:

Do not store auth tokens in Local Storage

OK, not convinced? There is nothing to read further for you. 

Go away!

But if you want to still use cookies... please continue.

The whole setup is not straight forward, especially now that the Laravel structure has changes, as you may know there is no more app/Http/Kernel.php where we use to set this kind of things.


Wait! Why? How?
Where is it?

Well, it's gone. And it will not come back!
Fook!

But, this is not the reason to set Laravel to a side and start looking for another framework  - if there is another framework...

So, how to set this bloody thing?

Step 1: Install Sanctum

If you already not having it, install it:

                    php artisan install:api
                  

Step 2: add SANCTUM STATEFUL DOMAINS to .env

                    SANCTUM_STATEFUL_DOMAINS='127.0.0.1:8001' #your domain
                  

Step 3: add settings to app.php

Open bootstrap/app.php and add these lines within the ->withMiddleware(function (Middleware $middleware) {

                    ->withMiddleware(function (Middleware $middleware) {

$middleware->api(prepend: [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,

];

});
                  

Step 4: Send JS API request with credentials

Do not forget to send withCredentials: true when sending JS request to the server

                    $.ajax({
                method: "POST",
                cache: false,
                xhrFields: {
                    withCredentials: true
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: url,
                data: sendData
            })
                  

Step 5: Update  AppServiceProvider.php

Open App\Providers\AppServiceProvider.php and add this code:

                    use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Auth;

public function boot(): void
    {

        $this->configureRateLimiting();
...


protected function configureRateLimiting()
    {
        RateLimiter::for('api', function ($request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }

                  

And

that

is

it.