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

barakuda28's avatar

Ajax calls flood causes TokenMismatchException

Hi everyone,

I am using Laravel 5.

I have a calculator feature on my site, which makes many AJAX calls to a route (via POST) and as you know CSRF is enabled for all routes by default, which is nice. But the problem is that if I try to flood it (make it generate like 100-200 requests) then it starts to throw a TokenMismatchException. I am passing the _token value properly. It normally works, excluding the cases when you try to flood it.

I am afraid that this behavior could occur for a regular user and then the calculator will stop working. I am not sure why it happens. Could you please explain and give me an idea for solving it?

The easiest way is to turn CSRF off for this particular route, but I am sure there must be a better solution to this. Thanks!

0 likes
5 replies
khoanguyenme's avatar

CSRF is very wierd, I often get this error on my website. The simplest solution is make a new route to return CSRF token. When server return with CSRF token error, get a new token from server and replace the old one

toniperic's avatar

CSRF token is re-created on every page request, which means you must've probably clicked on some link within your app (perhaps opened in a new tab?), and that request has set the token value to something other than what was the value of _token hidden input field within that form, and then tried to send the same form, but tokens wouldn't match anymore. Usually, it would work for any number of requests as long as you don't open any other page/do another request within your app, as it will re-create the CSRF token.

barakuda28's avatar

I read at StackOverflow that the token is permanent for the user's session. By default Laravel's session lasts for 2 hours. I just tried it and the token doesn't get reset when I open different pages, but it seems to have some flood protection. I can't find any documentation on it...

ashitvora's avatar

Anybody found solution to this? I'm facing this similar issue.

pmall's avatar

I think nobody will flood 200 requests on the same route. I think it is a timing issue per user, which is no problem.

Please or to participate in this conversation.