0

I see there are two ways Magento2 renders content in the header for logged-in vs logged-out customers.

  1. With KnockoutJS in header.phtml
  2. With PHP in customer.phtml

Which is considered best practice?

The second approach seems better for faster rendering of the content but I would have thought it would have caused issues with private-content, but Magento uses it here, how does this not cause an issue with caching?

2

It seems for private content which is specific to a user, such as minicart, user-name etc. It is correct to use KnockoutJS/JavaScript to retrieve personalised data with Ajax requests or with Magento's customerData JS component.
This data cannot be cached on the server side.
e.g. header.phtml

However for content which is not unique to a specific user, but which is different per page variation.
It can be cached on the server side, with Magento's use of HTTP context variables. For example if a customer is logged in or not.
For example, this is what is happening with customer.phtml which is using httpContext to serve different content from the cache for requests origination from the same URL depending on if the user is logged in or not.

I found these blog posts helpful:
https://www.atwix.com/magento-2/cache-context-and-page-variations-in-magento-2/
https://www.interactiv4.com/e-commerce-en/almacenamiento-en-cache-en-magento-2-i4/?lang=en

As well as the documentation:
https://devdocs.magento.com/guides/v2.3/extension-dev-guide/cache/page-caching/public-content.html#configure-page-variations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.