3

We are attempting to show a users first name on a profile menu for authenticated users. We added a lazy builder to the hook_preprocess_page hook in our theme given this is highly dynamic content on heavily cached pages.

if ($account->isAuthenticated()) {
  $vars['current_user_first_name'] = [
    '#create_placeholder' => true,
    '#lazy_builder' => [
      '\Drupal\ourtheme\OurThemeLazyBuilders::getUserFirstName',
      [$account->id()]
    ]
  ];
}

With this callback (inside of a class that implements RenderCallbackInterface)

public static function getUserFirstName($account_id) {
    $user = User::load($account_id);
    return [
      '#plain_text' => $user->field_first_name->value,
      '#cache' => [
        'max-age' => 0
      ],
    ];
  }

However, when two of us (both administrator accounts) log in, whoever logs in second will see the other persons first name. We have verified the caching issue by setting a breakpoint in the hook_preprocess_page hook and see that the breakpoint never gets hit for the second users request. We tried moving the lazybuilder into it's own block and placing that block in a region of our theme, this didn't seem to make a difference, we saw the same caching behavior.

Interestingly, this only seems to happen when the users have the administrator role, we have thousands of other active users who only have authenticated users role and we've not heard anything about this issue from them (we would have heard immediately if there was an issue for general users).

Is there a way to debug the caching system in Drupal to know what parts of a page are cached by the dynamic cache and/or page cache?

1 Answer 1

5

Don't pass the user ID to the lazy builder, arguments get cached. Get the current user ID in the lazy builder:

public static function getUserFirstName() {
    $account_id = \Drupal::currentUser()->id();
    $user = User::load($account_id);
    return [
      '#plain_text' => $user->field_first_name->value,
      '#cache' => [
        'max-age' => 0
      ],
    ];
  }
4
  • Would they also get better performance by setting a cache context for the current user instead of max-age?
    – mona lisa
    Commented Aug 31, 2022 at 18:04
  • 4
    Probably the opposite - it’s not recommended to vary by current user as that produces a lot of variations, and obviously increasing exponentially as the user base grows
    – Clive
    Commented Aug 31, 2022 at 18:14
  • Thank you! You have solved a few day old mystery....knew it had to be something like that! Commented Aug 31, 2022 at 19:04
  • @Clive is almost certainly correct.
    – mona lisa
    Commented Aug 31, 2022 at 19:06

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.