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

MarkMatute's avatar

TokenMismatchException

TokenMismatchException occurs only sometimes, works on Mozilla not in Chrome

0 likes
10 replies
MarkMatute's avatar

@opheliadesign its happening on login, every time i start the project some times it says this error upon login TokenMismatchException in VerifyCsrfToken.php line 53:

opheliadesign's avatar

@MarkMatute I'm guessing this might be because you're leaving the login form on the screen for a couple of hours and the session token is expiring.

2 likes
Kryptonit3's avatar

@opheliadesign I ran into that exact scenario on a site I made for my company. Techs were leaving their order page up and tried to submit an order the next day and BAM, error. I then implemented a simple ajax request that runs every few seconds to a method on my controller that returns value of auth()->check() and if it ever returns false, a non-dismissable modal with a message and link to the login page automatically pops up.

opheliadesign's avatar

@Kryptonit3 this is how I solved the issue in 5.1. I can't take full credit for this but I can't remember where I learned it and I think I pieced a few bits together: App\Exceptions\Handler.php

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof TokenMismatchException) {
            //Redirect to login form if session expires
            return redirect($request->fullUrl())->with('errors',
                ["The login form has expired, please try again. In the future, reload the login page if it has been open for several hours."]);
        }
        return parent::render($request, $e);
    }
2 likes
Kryptonit3's avatar

@opheliadesign the only problem I see with that is a TokenMismatchException isn't directly tied to an expired session. I have gotten them before for a number of different reasons.

But this is a good method for catching it. I personally would reword it to something along the lines of a general error

The form has expired, please try again. In the future, reload the page if it has been open for several hours.
MarkMatute's avatar

I figured it out though :) everytime i ran into this problem i do this ''' get('regentoken',function(){ return csrf_token(); }); ''' but i dont know what would be a good long term solution

pmall's avatar

@Kryptonit3 You can also regenerate the token with js right after they click on the submit button, and send the form only when the token has been regenerated. This avoid to reload the token every few seconds.

Please or to participate in this conversation.