DEV Community

Cover image for A rare situation when Laravel's session regenerates on each request in some specific servers
Mojahidul Islam
Mojahidul Islam

Posted on

A rare situation when Laravel's session regenerates on each request in some specific servers

Hello Nerds,

I recently had a situation where I faced a weird problem with Laravel's session after migrating from Laravel 8 to Laravel 10. The thing was my application was regenerating the session on each request. Thus, resulting errors with TokenMismatchException and causing to 419 (page expired) error.

The fun fact is it was happening in only a specific server of a platform named siteground and was perfectly fine in my other WHM based shared hosting and Ubuntu VPS.

It was very hard to debug since the problem only occurred in a very specific server and I tried almost every suggestion I got from the internet to fix this problem for that specific server. But none of them work.

After several trials and errors, I finally figured out it sacrificing 2 nights of my precious sleep. If you are having the same problem as me and tried every trick on the book (the internet I mean) and still weren't able to fix this issue here is what you gotta do. You will probably laugh at yourself when you find out the root cause (if the scenario is similar that is).

  1. Check all of your configs and see if any of them have an empty line before the php tag and remove it.

  2. Check every file that are being autoloaded like Providers, Helpers etc and check if they have any empty line before the php tag and remove it.

  3. Ultimately you can use the below regex to find this specific pattern and get rid of it entirely from your project using a global search and replace feature of your IDE

Search with: ^\s*\n\s*<\?php
Replace with <?php

I hope this help you (and my future self) fix the problem regarding the Laravel's Broken Session that had been a pain in my ass for a whole week.

Have a great day,
Keep breaking things, Nerd!

Top comments (0)