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

shangsunset's avatar

csrfTokenMismatch exception after session timeout

in our laravel app, the login is through ajax. if user logout and log back in before session expires, everything is fine. but if user logout and stay idle on that page until session is expired, user will get a csrfTokenMismatch exception if they attempt to log back in.

i know in verifyCsrfToken middleware, laravel checks if session matches with the csrf token. also in Guard.php logout() method, session will be cleared on logout.

so my questions are:

is session really flushed on logout, if so how come user can still log back in before the session i set expires?

what happens to csrf token when session is expired?

and lastly, how is this issue usually handled in an elegant way?

Thanks in advance!

0 likes
3 replies
jekinney's avatar

If your doing it by Ajax call via JavaScript, no the session is not cleared out as your not refreshing the page and session. The token is stored in the old session as you stated. You can store sessions elsewhere or manually refresh the session which would require your JavaScript to update the token or reflash the current one again.

shangsunset's avatar

hey @jekinney, so when i logout, the page will be refreshed, that means the session will also be refreshed correct? also, can you explain your last statement with more detail - "You can store sessions elsewhere or manually refresh the session which would require your JavaScript to update the token or reflash the current one again."

how would you refresh the session and update the token with js?

Thanks.

Please or to participate in this conversation.