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

PKarag's avatar
Level 3

Check if session is still active via ajax

Hello community,

Im trying to implement a feature where the frontend will periodically check if the session is still active and prompt the user to relogin or even redirect him to login page. The problem is that this ajax request itself will result in the session refreshing, resulting in a nonexpiring session. Ive tried messing up with creating a custom StartSession middleware and override its logic but it seems to always result in a session refresh. My session driver is Redis.

Interestingly enough, the below code would work, since the dd() statement will stop any further execution, but feels wrong and hacky.

public function sessionCheck()
    {
        if (!auth()->check()) {
            throw new \Illuminate\Auth\AuthenticationException('Unauthenticated');
        } else {
            dd('Session is active');
        }
    }

Anyone have any solution on how I could stop the request from refreshing the session?

Thanks in advance!

0 likes
2 replies
LaryAI's avatar
Level 58

To implement a feature where the frontend periodically checks if the session is still active without refreshing the session, you can use a custom middleware to handle the session check. The key is to avoid touching the session in a way that would refresh it.

Here's a step-by-step solution:

  1. Create a Middleware: Create a custom middleware that will check if the user is authenticated without refreshing the session.

  2. Register the Middleware: Register the middleware in your Kernel.php.

  3. Create a Route and Controller Method: Create a route and a controller method to handle the AJAX request.

Step 1: Create a Middleware

Create a new middleware using the Artisan command:

php artisan make:middleware CheckSession

In the CheckSession middleware, add the following code:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckSession
{
    public function handle($request, Closure $next)
    {
        if (!Auth::check()) {
            return response()->json(['authenticated' => false], 401);
        }

        return $next($request);
    }
}

Step 2: Register the Middleware

Register the middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    // other middlewares
    'check.session' => \App\Http\Middleware\CheckSession::class,
];

Step 3: Create a Route and Controller Method

Create a route in routes/web.php or routes/api.php:

Route::get('/session-check', 'SessionController@check')->middleware('check.session');

Create a controller method in SessionController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SessionController extends Controller
{
    public function check(Request $request)
    {
        return response()->json(['authenticated' => true]);
    }
}

Frontend AJAX Request

Finally, you can set up your frontend to periodically send an AJAX request to the /session-check endpoint:

function checkSession() {
    fetch('/session-check')
        .then(response => {
            if (response.status === 401) {
                // Session is not active, redirect to login page
                window.location.href = '/login';
            } else {
                return response.json();
            }
        })
        .then(data => {
            if (data.authenticated) {
                console.log('Session is active');
            }
        })
        .catch(error => {
            console.error('Error checking session:', error);
        });
}

// Check session every 5 minutes
setInterval(checkSession, 5 * 60 * 1000);

This approach ensures that the session check does not refresh the session, and it will redirect the user to the login page if the session is no longer active.

PKarag's avatar
Level 3

@LaryAI Sadly this still results in the session getting refreshed.

Please or to participate in this conversation.