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

rktaxali's avatar

How to handle session timeout in Laravel 9 application?

In my Laravel 9 application that uses Auth, I make extensive use of Ajax calls. I also have a timer on one page that makes an AJAX call every minute. Now consider a situation that the user has left the application running and the timer is making an AJAX call every minute and the session times out. Now that AJAX call will fail.

What is the easiest way to detect session timeout, so that AJAX calls don't end up in an error situation? I would like to automatically logout the user and redirect the user to 'session timed out' page. I would prefer to handle this in routes/web.php where all routes are contained or at some other central place.

Any help is greatly appreciated.

0 likes
7 replies
LaryAI's avatar
Level 58

One solution to handle session timeout in Laravel 9 application is to use Laravel's built-in middleware called "AuthenticateSession". This middleware checks if the user's session is still valid and if not, it logs out the user and redirects them to the login page.

To use this middleware, you can add it to the "web" middleware group in your "app/Http/Kernel.php" file:

protected $middlewareGroups = [
    'web' => [
        // ...
        \Illuminate\Session\Middleware\AuthenticateSession::class,
    ],
    // ...
];

Once you have added this middleware, you can create a custom middleware that checks if the user's session has timed out and redirects them to a "session timed out" page. Here's an example of how you can do this:

<?php

namespace App\Http\Middleware;

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

class CheckSessionTimeout
{
    public function handle($request, Closure $next)
    {
        if (Auth::check() && ! $request->session()->has('lastActivityTime')) {
            $request->session()->put('lastActivityTime', time());
        }

        $maxIdleTime = config('session.lifetime') * 60;

        if (Auth::check() && $request->session()->has('lastActivityTime') && (time() - $request->session()->get('lastActivityTime') > $maxIdleTime)) {
            Auth::logout();

            return redirect('/session-timeout');
        }

        $request->session()->put('lastActivityTime', time());

        return $next($request);
    }
}

In this middleware, we first check if the user is authenticated and if the "lastActivityTime" session variable is not set, we set it to the current time. We then calculate the maximum idle time based on the session lifetime configuration value and check if the user has been idle for longer than this time. If so, we log them out and redirect them to the "session-timeout" page. Finally, we update the "lastActivityTime" session variable to the current time.

To use this middleware, you can add it to the "web" middleware group in your "app/Http/Kernel.php" file:

protected $middlewareGroups = [
    'web' => [
        // ...
        \App\Http\Middleware\CheckSessionTimeout::class,
    ],
    // ...
];

You can then create a "session-timeout.blade.php" view file and a route that points to it:

Route::get('/session-timeout', function () {
    return view('session-timeout');
});

Now, whenever the user's session times out, they will be automatically logged out and redirected to the "session-timeout" page. You can also customize this behavior by modifying the middleware or the view file as needed.

Snapey's avatar

if you are making regular requests as that user, why would the session timeout?

1 like
rktaxali's avatar

@snapey The requests are being made by a timer, something like to check if a new notifications is available. There is no user interaction. Do you think that the session should not timeout in this situation?

Snapey's avatar

@rktaxali If the ajax endpoint is in web.php then the request will keep the session going

If its in API then how do you authenticate who the request is from?

If the session times out I expect you could detect it in the ajax code and reload the window with the login page

rktaxali's avatar

@snapey Regarding the Ajax calls initiated from the timer, I would retest/recheck. However, I still need to detect session timeout from regular user initiated Ajax calls (e.g on pressing a button on page that was left inactive for 2 hours). I would try to implement the reply generated by AI

rktaxali's avatar

@snapey When the timer is used, the session does not timeout as you have mentioned. However, it I don't use timer and want the session to timeout and want to handle this from a central place, the answer provided above by AI works.

m7vm7v's avatar

Snapey definitely has some point on the question tho. If the request is failing then the ajax call seems to be executed in the wrong middleware, I could be wrong on that depending on your system of course.

You could also try on the ajax call to have a

    .fail( function(xhr, status, error) {
        if (status is the one you need and the error is that number) {
			redirect to the page you want
		}
    });
1 like

Please or to participate in this conversation.