api routes are, and should be, stateless.
May 27, 2024
3
Level 3
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
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.