How to use Http caching with logout form

Hi guys,

I would like to use http caching on my application to take advantage of browser caching. I’ve configured a few controllers to use it and it works. However I’m facing a problem with the logout option in the top menu. The logout uses a form to make a post which include the csrf token like the advanced template. Sometimes I get a 400 bad request when trying to logout because the csrf token comes from the cached page and I believe it’s not good anymore. This scenario occurs if I login into my application then close the browser then reopen it (I’m still logon) and finally try to logout. I have to ctrl-F5 to force the csrf token to refresh to be able to logout.

I would like to know how you guys manage this situation. I guess I’m not the only one with a logout menu.

Thanks for your input.

Alex

Also why there is a csrf token in the head tag and in the form? Which one is use and when?

Do you actually need this page caching right now or are you just exploring this because you are trying to "solve" this potential issue in the far future?

I have a feeling it’s the latter, in which case you shouldn’t be worrying about it at all until you start getting real scaling issues. It’s called premature optimization, and most of the time slow performance is actually caused by database calls (either too many or not properly indexed).

Anyway, the real answer is that you don’t handle this via php. Instead you should be sticking more services in front of your app, eg, varnish or haproxy (caching and/or load balancers).

Thanks for your help.

Well it might be premature optimization. I deployed my site in production like two monthes ago. I don’t have much traffic yet. I wanted to use caching because I received a warning by my hosting company that I used more than 75% of CPU. It happened only one time, so it might be too soon.

My hosting company already offers vanish as intermediate cache. But it’s not of great help for this case because it returns the logout form to everyone with the same CSRF token which obviously returns a 400 bad request when someone tries to logout.

I start realizing that it won’t probably be possible to use the vanish caching for my pages even if the only thing that differs in pages is the CSRF token.

To use http caching I don’t see any solution apart from loading the main content of pages by ajax so the header with the logout form doesn’t load every times. Another way would be to let down http caching and use other caching mechanisms provided by Yii2 but I’m affraid it would be less effective.