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

somenet77's avatar

Session store not set on request with api route

I have created a next-breeze frontend authentication. and created an API route like this

Route::prefix('v1')
    ->group(function () {
        Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
            return $request->user();
        });
        
        Route::controller(App\Http\Controllers\Api\V1\Auth\AuthenticatedSessionController::class)
            ->group(function () {
                Route::post('/login', 'store');
                Route::post('/logout', 'destroy');
            });
});

which works fine in local development. But when I push to production I get the above error. Then I put a

\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,

classes in API middleware also like this

'api' => [
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

But the wired issue I faced is when I log in to the next app the admin panel automatically logout if the admin panel is logged in

0 likes
3 replies
Snapey's avatar

api routes are, and should be, stateless.

somenet77's avatar

@Snapey Actually my frontend and backend are in two different subdomains. In that case how to fix this issue. In Laravel documentation, I got this https://laravel.com/docs/11.x/sanctum#spa-authentication

In order to authenticate, your SPA and API must share the same top-level domain. However, they may be placed on different subdomains. Additionally, you should ensure that you send the Accept: application/json header and either the Referer or Origin header with your request.

frontend.example.com = frontend

backend.example.com = backend

somenet77's avatar
somenet77
OP
Best Answer
Level 3

And i fixed my solution like this

in .env file

SESSION_DOMAIN=".example.com" 

in config/sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,*.example.com',
        Sanctum::currentApplicationUrlWithPort()
    ))),

Please or to participate in this conversation.