Magento – Magento 2: How to disable caching for the header block

cachingheadermagento2

I just go through other similar questions but they didn't help much. As per suggested in some answers to put the cacheable="false" in block will disable it.

But it will disable whole page caching as per this documentation and here if that block is exist in any page.

I have an issue that after customer login in system, in header still showing the login link and showing wrong user name due to caching.

Is there any way I can exclude the header block from caching?

Best Answer

The customer specific data(private data) is not a part of the public content, so there is no need to disable caching using cacheable attribute.

Regarding the issue, the proper section of documentation is http://devdocs.magento.com/guides/v2.2/extension-dev-guide/cache/page-caching/private-content.html

The private data is stored in browser local storage. This data is cleaned up using the rules described in section.xml files. For your case, the xml will be like following:

<action name="customer/account/logout"/>
<action name="customer/account/loginPost"/>
<action name="customer/account/createPost"/>
<action name="customer/account/editPost"/>
<action name="customer/ajax/login">
    <section name="checkout-data"/>
    <section name="cart"/>
</action>

It means that browser will flush the data in local storage on every POST request to the urls described above (except /customer/ajax/login - for this case Magento do only partial cleanup). So, to fix your issue you need to check:

  • The login URL is present in some section.xml file. If no, just add it in custom module
  • Your Magento instance uses POST request to login URL
  • Make sure you don't have any JS errors in the browser console, which might prevent JS from cleaning the local storage
  • Make sure that private data is not a part of the public content. It must be delivered only using section sources