I have removed "Access Content " Permission from Anonymous user. Now want to display specific node to the anonymous user.

As this is for only 1 or 2 nodes, It's not a good idea to use a contributed module like https://www.drupal.org/project/access_by_entity. I am looking for a solution as a custom code only

I have tried mymodule_node_access also but it's not working.


An access hook can't change the result once you have forbidden access by removing the permission "Access Content", see Is there a way to add node grants to anonymous users?.

If you don't want to grant this permission, because it controls much more than node access, another approach might be to setup a route which bypasses permissions and checks the node ID instead:


  path: '/path_to_my_nodes/{node}'
    _entity_view: 'node.full'
    _access: 'TRUE'
    node: (123|124)

Give back the "Node access" permission (View published content) to Anonymous user and control the accesss with your custom module

use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;

function MODULENAME_node_access(NodeInterface $node, $op, $account) {
  $allowed = [1,2];
  if ($op == "view" && in_array($node->id(),$allowed)) {
    return AccessResult::allowed();
  return AccessResult::forbidden();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.