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

santhusurya's avatar

How to handle Ajax requests from pages after User Session has expired(user logged out)

In a Laravel app with user authentication, how to handle Ajax requests made after User session has expired(User Logged out)?

As observed, Ajax requests made after session expiration are getting redirected to Login page at the server end, but at the client end Ajax request fails!

How to make out the status of the Ajax request failing because of Laravel User Session expiration & other causes of failure.?

Is there a standard approach to notify the user that the Session has already expired & they need to login again to continue making Ajax requests?

0 likes
4 replies
santhusurya's avatar
santhusurya
OP
Best Answer
Level 2

I was able to find out the working solution on my own for above mentioned problem!

I'm mentioning the solution below, if at all anybody needs the solution for similar problem! :-)

Step 1. Create & Register New Middleware

class CheckSessionAjaxRequests
{
/**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->ajax()) {
            if(empty(Auth::user())){
                return response()->json([
                    'SESSION_STATUS' => 'NOT_LOGGED_IN'
                ]);
            }
            else{
                return $next($request);
            }
        }
        else{
            return $next($request);
        }
    }
}

This middleware checks for AJAX requests but bypassing normal HTTP requests. As the main issue was to have a mechanism to handle AJAX requests after the User Session has expired.

Other Normal HTTP requests failing due to User Session expiration will be handled by other default middlewares. This will continue to work as earlier.

if($request->ajax()) {
            if(empty(Auth::user())){
                return response()->json([
                    'SESSION_STATUS' => 'NOT_LOGGED_IN'
                ]);
            }
            else{
                return $next($request);
            }
}
 else{
            return $next($request);
 }

Here if condition checks whether the request is of AJAX type. If it's AJAX then in the next step, we will check whether there is an Authenticated User.

If no Authenticated User, then return the request with JSON data. Use this JSON data in your javascript & notify the user that the session has already expired & show them re-login modal/page.

If Authenticated Userfound, then continue with the request. Next other middlewares will handle this AJAX request.

Step 2. This step is very important! Please define below piece of code in Kernel.php file which you will find under app/Http/folder.

In order to make sure that your New Middleware CheckSessionAjaxRequests will first handle all requests coming to a route with many middlewares(middleware group) defined to it.

/**
     * The priority-sorted list of middleware.
     *
     * Forces the listed middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        'ajax.request' => \App\Http\Middleware\CheckSessionAjaxRequests::class,
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
/***** REST OTHER MIDDLEWARES, IF ANY *****/
    ];

In the above code we are explicitly defining the FIRST PRIORITY for the New Middleware by placing the middleware at the begin of the list. This way we can be sure, that CheckSessionAjaxRequests middleware will get handle of the request from any associated route & it will be first to take necessary action on the request. Only after this middleware, other middlewares defined in the $middlewarePriority will handle the request based on their priority.

Hope this approach/solution help someone.! :-)

teknocat's avatar

This actually does not work. I have tried Auth::check(), !Auth::guest() as well as checking if Auth::user() has a value. So long as a user is authenticated, regardless of whether their session has since expired, these functions all do nothing to help with a session expiry check. Auth::check() still returns true, Auth::guest() still returns false, and Auth::user() still returns a user.

Everywhere I search, it suggests the same or similar things, but this NEVER works no matter what I try.

teknocat's avatar

Actually it seems the middleware doesn't even kick in once the session has expired, so something I'm doing is amiss.

teknocat's avatar

So in Laravel 5.8, what I found resolved the issue for me was first adding my middleware class to the 'web' group in $middlewareGroups, right after StartSession.

Then, I made sure to include my middleware first in the route group, as follows:

Route::group(['middleware' => ['ajax-session-expired', 'auth']], function() {

Now my middleware runs before auth properly, and then using Auth::guest() or Auth::check() works as expected.

Please or to participate in this conversation.