Skip to main content

Drupal 9: Disable cache for a specific page

This is the "standard" way of disabling caching for a page in drupal ^8.


There is an issue though with this code. When you use this code what really happens is that the whole page is not being cached anymore. So for example if this the front page of your website this might be a perfomance issue. It does not matter if you use it inside a block or in your controller or somewhere else in your code. The call of this service will force the caching mechanism for the whole page to be disabled. It is also worth mentioning that this should be used for anonymous users since you have better control for "registered" - "logged in" users per block or per page.

As an alternative if this is a custom controller page for example you can use the specific option in the routing yml file as shown here (no_cache: 'TRUE').

  path: '/search-results'
    _controller: '\Drupal\custom_module\Controller\SearchResultController::index'
    _title_callback: '\Drupal\custom_module\Controller\SearchResultController::getTitle'
    _permission: 'access content'
    no_cache: 'TRUE'