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

yannik's avatar

Best way to handle invalid CSRF tokens

Hi,

by default, the CSRF middleware throws a (uncaught) TokenMismatchException if a CSRF token is invalid, which then results in a generic 'Whoops' error page.

How do you guys handle these?

Would Redirect::back()->withInput()->withErrors('Detected CSRF attempt'); be sensible or are there any potential problems with this?

In which cases could a legitimate user actually send an invalid csrf token?

0 likes
3 replies
pmall's avatar

Yes but on production debug config var is falsy (at least it should be) so the whoop page isnt displayed.

Valorin's avatar

I've simply updated the default Whoops page to a generic, but themed, "something broke" page. I figure 99% of the time someone getting a CSRF error is doing something bad, so no harm done in telling them to get stuffed.

That said, you might be able to catch the exception further up the chain, like you can catch any ModelNotFoundException that may be thrown.

Please or to participate in this conversation.