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

yeasir_arafat's avatar

Middleware to check if ajax request is authenticated is not working

I am trying to handle ajax request that were initiated from idle/expired session(maybe the page was left open and the session got expired). I wrote the below middleware but it's not working as expected:

namespace App\Http\Middleware;

use Closure;

class AjaxSessionCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!\Auth::check())
        {
            if($request->ajax())
            {
                return response()->json(['Session_error'=>'Session Expired'], 401);
                //throw new AuthenticationException('Unauthenticated');
            }
        }
        return $next($request);
    }
}

To check this i logged in to the same page that contains the form from two separate tabs and then logged out from one of the tab, making the session invalid on the other tab as well. Then i initiated an ajax request(user clicks a delete button).

Any help to the right direction will be much appreciated!

0 likes
2 replies

Please or to participate in this conversation.