1

I have a custom Drupal 8 block with class with build() and getCacheMaxAge() functions. getCacheMaxAge() is set to 0 but it is still being cached for anonymous users.

If I put debug code in the build() function I can see it being called when I'm logged in but not for anonymous users.

My code is below. We do have Memcached installed. Would that be causing the issue?

The only other caching modules are core.

<?php
class HeaderPhone extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {

    $info = geo_location_blocks_get_region();
    $region = $info['region'];
    $tid = $info['tid'];

    return array(
        '#theme' => 'geo_location_header_phone',
        '#region' => $region,
        '#view' => views_embed_view('locations', 'block_3', $tid),
      
    );
  }

  /**
   * @return int
  */
  public function getCacheMaxAge() {
    return 0;
  }
}?>

  
4
  • You might need to add a max-age to the render array as well, using '#cache' => ['max-age' => 0]].
    – Jaypan
    Commented Aug 26, 2021 at 1:02
  • Thank you Jaypan, I tried adding #cache to the render array as suggested but the block is still caching for anonymous users. Commented Aug 26, 2021 at 1:06
  • Re-reading your post, memcached could be an issue. You could try disabling it and seeing if the problem persists. Or testing on an environmnent with memcache disabled. The other possibility is the page cache may be caching the whole page for anonymous users.
    – Jaypan
    Commented Aug 26, 2021 at 6:25
  • I ruled out memcached. I tested the issue on a site copy on a different server without Memcached and the issue is still there. Commented Aug 26, 2021 at 11:39

1 Answer 1

5

Setting cache max-age to 0 doesn't work if you still have the core module Internal Page Cache enabled.

Read the documentation why you probably want to disable this module or deliver the block with a different method:

Websites that serve personalized content to anonymous users (dynamic, per-session, e.g. a shopping cart) will want to disable the Internal Page Cache module. This module assumes pages are identical for all anonymous users. Those websites can still take advantage of the Dynamic Page Cache module though, or can alternatively do their personalization using JavaScript + AJAX.

https://www.drupal.org/docs/administering-a-drupal-site/internal-page-cache

1
  • Thank you. the Internal Page Cache module was the issue. Commented Aug 26, 2021 at 11:44

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.