I am using hook_node_access to decide the whether a node should be visible to anonymous users based on their IP address. To prevent this being cached I am using \Drupal::service('page_cache_kill_switch')->trigger() within hook_node_view_alter, but if access is forbidden then hook_node_view_alter is not run and so the cache is not killed.

Where should I put \Drupal::service('page_cache_kill_switch')->trigger()? Is there a better way to do this?

1 Answer 1


I wouldn't use hook_node_access, it's rather static and with additional caching layers because it's called a lot of times, not only for incoming routes. IP-based code is best placed in a middleware or a request event subscriber with a higher priority. If you want to try the hook solution then put both, the kill switch and the access denied exception, in the same hook_node_view_alter and add a cache max age as well:

use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

  if ($node->getType() == 'article') {
    $build['#cache']['max-age'] = 0;
    if (...) {
      throw new AccessDeniedHttpException();

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.