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

dangelsaurus's avatar

TokenMismatchException caused by caching?

Is it possible to have a TokenMismatchException error caused by caching a page and reloading it? Let me explain.

I have a site I'm working on that requires a user to click on their favorite image, once they click an image, an ajax post request is sent to randomly load a new album. Right now the page submits as a form, therefore there is a csrf token inserted automatically.

Because I'm only working with a few albums and the selection is random, the same album often appears again. For some reason every 5-10 clicks I get a TokenMismatchException error, and then when the next album loads everything is fine for 2 or 3 more times and then the same error..

Is it possible that the ajax request is loading a cached page with an old token? If so, what is the work around?

0 likes
3 replies
vtalbot's avatar

The token expires after a couple of minutes. You could update the token by rendering a new token in the response after a post and updating your old token with it or you could add the uri of the ajax call to the $except array in the middleware VerifyCsrfToken.

dangelsaurus's avatar

how many "live" tokens can a session use at once? for instance if I have 2 forms on a page, both dynamically generated at different times, and therefore with different tokens. Does it matter what order they are submitted (in regard to having a valid token?)

It occurred to me that I MIGHT be submitting the 2nd token with the 1st form.. but if both tokens are active in the session, should i be ok?

dangelsaurus's avatar

Ok, looks like my token is changing and an old token is being submitted. I'm gonna create a new post to address the new issue

Please or to participate in this conversation.