in Laravel Development

Token mismatch exception Laravel 5.4 mystery – solved!

TokenMismatchException in VerifyCsrfToken.php line 46:

Now, we’re very familiar with this error but this week we found ourselves scratching our heads trying to understand why sessions were not persisting for a particular Laravel app we’ve been working on. We were consistently receiving a token mismatch exception error for every form submitted and as a result there we many confusing issues going on.

One particular issue we spotted in the ‘Application’ tab in Chrome. I could see cookies were not persisting and within the storage/framework/sessions/ directory, files were being added every time the page refreshed.

Another side effect of this bug was that the Laravel Debugbar styling broke entirely and the output of the bar trialed at the bottom of the page.


We tried a dozen or so fixes including:

  • Removing the middleware web route group
  • Reset permissions and ownership to ensure the files were being written correctly in the storage directory
  • Set SESSION_DOMAIN to ensure that the appropriate domain was being used when setting the cookies
  • Tried other drivers in the .env file by setting SESSION_DRIVER
  • Copying over all Laravel configuration files etc from a fresh build

None of which solved the issue for us.

Now the solution…

In the end, the fix was very simple (as it always tends to be), we have a helper.php file which had a single space at the start before the <?php start tag. The app started working as expected as soon as the space was removed.

Write a Comment