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.

\Drupal::service('page_cache_kill_switch')->trigger(); 

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').

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

 

cache