We are using Drupal 8.8.5. For every page we are trying to provide a counter which increments whenever user hits that node. These are nodes are available to anonymous users. So whenever an anonymous user hits the node, the view counter on that node should be updated to show the no of total hits . So lets say Tom and Hary are anonymous users. Tom hits node1. On top of Node1 it says "View 1" times. Now when Hary hits Node1 it should sat "View 2" times. Again if Tom hits node1 it should day "View 3" times. I checked How can I show node Hits (statistics)? and made the necessary code changes in basic.theme and node.html.twig. Still, it shows Viewed O times.

This is the code I have in the basic.theme file.

function basic_preprocess_node(&$variables) {
  $variables['node_view_count'] = 0;
  if (!empty($variables['node'])) {
    // Get the number of times the current node has been viewed.
    /** @var \Drupal\statistics\StatisticsViewsResult $statistics */
    $statistics = \Drupal::service('statistics.storage.node')
    if ($statistics instanceof StatisticsViewsResult) {
      $variables['node_view_count'] = $statistics->getTotalCount();

This is the code I added in the node.html.twig file.

Viewed {{ node_view_count }} times

I believe there might be a caching issue once it starts working. For each hit, the values should be updated.

On a side note, when I am using the Visitors module, the report is showing an updated page count even for anonymous users. I had to install the Advanced Page Expiration module, though.

How do I increment the node hit for anonymous user visits in each page and show it updated?

1 Answer 1


Ok i have resolved this using a database query and a custom block. Pre-req: Installing visitors module. Then having this query in the custom clock

public function build() {
  $node = \Drupal::request()->attributes->get('node');
  $uidValue = $node->getOwnerId();
  $urlValue = $node->toUrl()->toString();
  $database = \Drupal::database();
  **$query = $database->query("SELECT COUNT(visitors_path) AS visitors_path FROM 
(visitors) WHERE visitors_path='$urlValue' ");**
  $result = $query->fetchAll();
  $nodecounthit = $result{0}->visitors_path;
  echo "Viewed ".$nodecounthit." times";

this function ensured results were not cached.

 public function getCacheMaxAge() 
    return 0;

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.