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

shangsunset's avatar

How to handle TokenMismatchException when session expires on the client side

Greetings, friends!

How do you usually handle TokenMismatchException on the client side? I dont want to handle the exception by redirecting them to a log in page as all the requests are handled via ajax including authentication.

So my solution so far is: catch the mismatch exception in Handler.php and return a json response with a new token. on the client side, use the new token to continue the intended process. However, I couldnt renew the token for some reason. This is what i have:

setup csrf_token in a global js file:

   $(function () {
       $.ajaxSetup({
         headers: { 'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content') }
       });
     });

render method in app/exceptions/handler.php:

    public function render($request, Exception $e)
    {
        if ($this->isHttpException($e))
        {
            return $this->renderHttpException($e);
        }
        else if ($e instanceof TokenMismatchException)
        {
            if ($request->ajax()) {
                return response()->json([
                    'message' => 'TokenMismatchException',
                    'token' => csrf_token()
                ]);
            }
        }
        else
        {
            return parent::render($request, $e);
        }
    }

in authentication.js:

  $.ajax({
    type: "POST",
    url: "/auth/login",
    data: {
      "email" : $('#login_email').val(),
      "password" : $('#login_password').val(),
      'remember': $('#login_remember').is(':checked')
    },
    success: function(response) {
      if (response.message === 'TokenMismatchException') {
        console.log(response);  //message and token exist
        //if catch the exception, use the new token to set up the ajax headers and login again
           $.ajaxSetup({
             headers: { 'X-CSRF-TOKEN': response.token }
             });
        login();
      }
      console.log('logged in');  
    },
    error: function(xhr, status, err) {
    }
  });

for some reason, $.ajaxSetup in the callback is not resetting the headers with the new token, so calling login again in the callback yields an infinite loop.

what should i do differently. how should i renew the token on the client side?

thanks in advance.

0 likes
0 replies

Please or to participate in this conversation.