I need to track some basic usage statistics for a subset of my authenticated user roles in Drupal 9.

Is there a way to make the core statistics counter only count node views based on user roles? The three counters it provides are all I need, I just need them to only record certain user roles.

1 Answer 1


The statistics module adds a js library to the node build. You can remove it if you don't want to count the node:


 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
function mymodule_node_view_alter(array &$build) {
  $roles = \Drupal::currentUser()->getRoles();
  if (!in_array('special_role', $roles)) {
    if (isset($build['#attached']['library'])) {
      $key = array_search('statistics/drupal.statistics', $build['#attached']['library']);
      if ($key !== FALSE) {

This only works if the roles are altering permissions. If not, add a cache context for the user roles:

$build['#cache']['contexts'][] = 'user.roles';
  • That looks perfect thank you. I'm afraid I don't understand this line though This only works if the roles are altering permissions. could you explain what you mean by that?
    – tanbog
    Commented Feb 27, 2023 at 9:09
  • Normally every role has a different set of permissions. But you could create multiple roles with the same permissions and then use them to control things not directly connected to permissions, like here.
    – 4uk4
    Commented Feb 27, 2023 at 9:20
  • Sorry, I'm even more confused now. The snippet makes sense; it removes the statistics js library if the user doesn't have the correct role. Why does the cache context matter here? I don't plan on changing user roles, Or is the same modified node getting presented to multiple users?
    – tanbog
    Commented Feb 27, 2023 at 9:28
  • 1
    Yes, exactly. By default, the cached node is presented to any user having the same permissions.
    – 4uk4
    Commented Feb 27, 2023 at 9:30
  • That is somewhat counter-intuitive to me but does explain some odd behavior with user roles I've run into before...
    – tanbog
    Commented Feb 27, 2023 at 9:36

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.