I'm getting the name of my user that I load from the profile. It's works fine on my local, but on my prod, the firstname displayed is showing the name from the previous user. How do I prevent that ? This is how I get my data.

This is where I don't understand, I'm loading data by current user, but the user isn't the good one...

I have my "new" firstname only after clearing my website cache with drush

 * Implements hook_preprocess_HOOK().
function frr_menu_link_preprocess_menu__account(&$variables)
    $current_user = \Drupal::currentUser();
    $variables['firstname'] = FALSE;
    if($current_user->isAuthenticated()) {
        $entity_manager = \Drupal::entityTypeManager();
        $profileStorage = $entity_manager->getStorage('profile');
        $profileCustomerFound = $profileStorage->loadByProperties([
            'uid' => $current_user->id(),
            'type' => 'customer',
            'is_default' => 1,
            'status' => 1,
        if($profileCustomerFound > 0) {
            $customer = end($profileCustomerFound);
            $firstname = $customer->get('field_firstname')->value;
            $variables['firstname'] = !empty($firstname) ? ucfirst($firstname) : FALSE;
  • What do you mean by the "previous" user?
    – mona lisa
    Apr 7, 2022 at 15:43

1 Answer 1


This is likely because you must add cacheability metadata so Drupal knows to cache the content separately by user.

  • 3
    Obligatory mention - varying cache per user is not a great idea as the number of cache entries can get large. Lazy builders and placeholders can be used in this sort of scenario. There's a good post with examples here: qed42.com/insights/coe/drupal/…, and if you search this site for lazy_builder there are plenty of other examples and explanations
    – Clive
    Apr 7, 2022 at 19:54
  • My website has about 160000 user for now, with the "dev" amount of users I have no problem... So can I add cacheability metadata ?
    – lobafox
    Apr 8, 2022 at 6:39
  • If so, how do I do this ?
    – lobafox
    Apr 8, 2022 at 6:40
  • 3
    If you have this amount of users then add $variables['#cache'] = ['max-age' => 0]; to prevent the menu to be cached for every user visiting the page. In this case a lazy builder is not absolutely necessary because menus are usually rendered in blocks and blocks have already a lazy builder.
    – 4uk4
    Apr 8, 2022 at 7:16
  • 2
    Although a separate lazy builder only for $variables['firstname'] would be nice. This makes the page load more fluid when the dynamic parts are restricted to the absolute minimum. See drupal.stackexchange.com/questions/305479/…
    – 4uk4
    Apr 8, 2022 at 9: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.