3

I need to invalidate the Internal Page Cache for anonymous users when the value of a specific cookie changes. How can I implement this?

I'm tried to add:

$build['#cache']['contexts'][] = 'cookies:my-cookie-name'

in hook_entity_build_defaults_alter, but that doesn't help. And the page still returns from the cache.

3

The Internal Page Cache doesn't support cache contexts. It is a simple reverse proxy designed to serve static database content and the only Drupal specific feature it has is to invalidate cache tags. For more dynamic use cases you have to uninstall this module.

The Dynamic Page Cache will then be the frontend cache for anonymous traffic. It is not as fast as the Internal Page Cache, though, so if it doesn't provide the performance you need consider a third-party reverse proxy which is able to handle cookies dynamically.

  • do you know any example of where a reverse proxy able to handle cookies has been implemented? – hugronaphor Apr 29 at 13:48
  • 1
    Normally a reverse proxy either filters a cookie or denies caching and you can configure this behavior. The Drupal built-in page cache does nothing of this. – 4k4 Apr 29 at 14:02
  • Hmm,OK. The thing is that I have a custom entity type and I was expecting that only while viewing its page I can somehow create more cached versions of the page depending on the cookie. – hugronaphor Apr 29 at 15:22
  • If this is only for specific entity routes then you can add a no_cache route option, see drupal.org/node/2463533. This disables page caching entirely, though, also the dynamic page cache. – 4k4 Apr 29 at 15:45
  • I found a way to implement it by extending PageCache class and I described it here cornel.co/article/drupal8/… – hugronaphor Jul 1 at 20:37
1

You have to override the PageCache::getCacheId method by adding the cookie value to form the Cache ID.

Have a look at Page Cache by cookies example.

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.