Score:0

How can I prevent a specific node type from caching for anonymous users (when using hook_node_access)?

bv flag

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?

Score:1
cn flag

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;
    \Drupal::service('page_cache_kill_switch')->trigger();
    if (...) {
      throw new AccessDeniedHttpException();
    }
  }
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.