I'm trying to submit an extension for Magento 2.4 but can't pass the "Varnish Test" stage because of the cache that can't be set up on some pages (simple-product and category):

"Expected HIT on the second page load.": ...
"Expected HIT on the second page load after product price update.": ...

I suppose in my case this error is due to the fact that I create cookies from my module code which could prevent the activation of the Varnish cache.

I have created two Observers on "controller_front_send_response_before" and "controller_action_postdispatch" events in which I create cookies with product information. I then retrieve and process this data from the front in JavaScript.

For my local tests, I have activated the varnish cache. When I request a product page or a category I can see the header "X-Magento-Cache-Debug: HIT".

Do you know if there are any special recommendations to follow regarding the creation of cookies in Magento 2 while allowing Varnish caching?

Thank you in advance,

  • AFAIK Magento's Varnish VCL caches in the presence of cookies. Your problematic point is probably setting them on every request, which results in sending negative caching headers and hitting this code. Since you consume the cookies in Javascript, why not simply emit things directly into HTML/Javascript code, by your module. – Danila Vershinin Sep 7 '20 at 15:45
  • Hello Danila, thank you for this feedback. I use this approach because I couldn't find any other way to format and return javascript code from Observers. For example, I detect "add to cart" events (event checkout_cart_add_product_complete). During such an action I retrieve all the information related to the product clicked in my Observer and add this data to the registry. Then, on a "controller_action_postdispatch" type event I read this registry and create my cookie which will be processed later on the front side. Do you know another way to proceed? Thank you – sonicso Sep 24 '20 at 9:01

Your Answer

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

Browse other questions tagged or ask your own question.