In my laravel/inertia/vue application I’d like to check if the session is expired or not. If the session has expired, a popup should be displayed. The check is done by making a call to the backend. I’m using the session database driver.
In the backend – as a matter of fact, it will be moved to a controller if working accordingly:
Route::get('/session-status', function (IlluminateHttpRequest $request) {
$sessionId = cookie(config('session.cookie'));
if (!IlluminateSupportFacadesAuth::check()) {
return response()->json(['session_expired' => true], 401);
}
// Fetch session directly from the database (without updating last_activity)
$sessionId = $request->session()->getId();
$session = IlluminateSupportFacadesDB::table('sessions')
->select('last_activity')
->where('id', $sessionId)
->first();
if ($session) {
$sessionLifetime = config('session.lifetime') * 60;
$sessionAge = now()->timestamp - $session->last_activity;
if ($sessionAge > $sessionLifetime) {
return response()->json(['session_expired' => true], 401);
}
}
return response()->json(['session_expired' => false]);
})->name('session.status');
In the frontend a simple axios call is made:
const showPopup = ref(false);
const checkSession = async () => {
try {
await axios.get('/api/session-status');
} catch (error) {
if (error.response && error.response.status === 401) {
showPopup.value = true;
}
}
};
// Run session check every 1 minute
onMounted(() => {
setInterval(checkSession, 6000);
});
I’ve tried many many options, but laravel keeps on renewing the session if the session is still active. This is nice behaviour when working in the application, but undesired for just checking the session status, as it creates a “drip” keeping the session alive forever.
Anybody a solution?