X-Magento-Vary aka HTTP Context
This week I've decided to better understand X-Magento-Vary cookie. In Magento 2 there might be more than one unique information presented to a user from same URL.
X-Magento-Vary cookie is used by Magento 2 system to highlight that version of a page requested by a user has been changed. It allows to have different versions of a same page stored in cache e.g. Varnish.
How it works
Any time a user performs an action e.g. Log in, subscribe to a newsletter, add to cart etc. this action changes state of a system. This state is also known as HTTP context of a system.
The context is identified by various unique parameters which are used to generate unique md5 hash value. Once generated, hash value is set into a X-Magento-Vary cookie parameter and sent back in a HTTP response.
The X-Magento-Vary cookie is set during HTTP POST or PUT request has been sent to a Magento application.
Varnish server configured as a front-end cache creates new version of a page based on newly generated X-Magento-Vary cookie.
In order to generate hash value Magento 2 uses parameters which help to differentiate different versions of a same page and with different content on it.
- “Customer Logged In” parameter is set every to differentiate a page for all guests versus specific information which is only available for logged in customers.
- “Customer Group” parameter provides information about logged in customer and customer group assigned for a customer. It works when there are catalog price rules or shopping price rules are applied on for a customer group.
- “Customer Segment” parameter provides similar to customer group information. It allows to additionally split customers to a different segments e.g. age, total order value in order to increase market such customers better. You may find this parameter in Enterprise version only.
- “Store” parameter is used to show different versions of a page per store.
- “Current Currency” parameter is used to have different prices on a page according to a currency selected.
- “Tax Rates” parameter affects prices on pages. Having logged in customer with shipping and billing addresses allows system to change taxes per customer depending on Tax Rate for a country.
Sometimes for one page stored in Varnish you may have up to 200 different versions of a same page.