Politeboat36 started a new conversation+100 XP
6h ago
Hello,
I have a Laravel + Inertia application that uses a serverless database that takes around 30 seconds to wake up. By default, Laravel stores sessions in the database, so when someone visits the home page while the database is shut down it shows a blank screen with no UI until the database wakes up and handles the user session store query.
I wanted to see if others here have faced the same problem and think the solution I have is sufficient or if additional measures are needed. The solution I have seems deceptively simple.
I believe what would work is to create a custom StartSession middleware like so:
<?php
namespace App\Http\Middleware;
use Illuminate\Session\Middleware\StartSession as Middleware;
class StartSession extends Middleware
{
public function handle($request, \Closure $next)
{
if (!auth()->check()) {
defer(function () {
app('db')->select('SELECT 1');
});
$request->setLaravelSession(app('session')->driver('array'));
return $next($request);
}
return parent::handle($request, $next);
}
}
And register it in bootstrap/app.php:
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Inertia\Inertia;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
], replace: [
\Illuminate\Session\Middleware\StartSession::class => \App\Http\Middleware\StartSession::class,
]);
})->create();