There's the cookies and cookies:MY_COOKIE_NAME cache context from core. Now 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 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.

2 Answers 2


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.

  • The linked example works beautifully, and is well described (I had the same question as OP, and solved it using this pattern). I think it should be marked as the accepted answer.
    – RominRonin
    Commented Feb 4, 2020 at 13:20
  • Thanks, this answer really saved me Commented Dec 21, 2021 at 14:45

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? Commented Apr 29, 2019 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.
    – 4uk4
    Commented Apr 29, 2019 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. Commented Apr 29, 2019 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.
    – 4uk4
    Commented Apr 29, 2019 at 15:45
  • 2
    I found a way to implement it by extending PageCache class and I described it here cornel.co/article/drupal8/… Commented Jul 1, 2019 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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