Back to Blog

Hide Drupal Test Pages from Visitors by IP Address

Build a Drupal style guide page combining all your UI elements, then restrict it by IP address so only your visual testing tool can reach it.

Yuriy Gerasymov
Yuriy Gerasymov
11 Jul 2024 · 1 min read

When you do visual regression testing, it can be a great idea to have some dedicated pages with all the different elements of your site combined. So instead of running screenshots of many pages on your site, you could do just a few and cover all the UI. These are also sometimes called style guides.

On the other hand, you do not want your site visitors to accidentally open these pages and be surprised by what they are for.

One of the approaches to hide these pages could be setting up access rules to only allow certain IP addresses (like Diffy’s IP address) to access those pages.

Here is a code snippet that can do that for your regular nodes.

<?php

/**
 * Implements hook_entity_access().
 */
function HOOK_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {

  // Only allow access to the test page.
  $testPageNid = 111111;
  if ((int) $entity->id() !== $testPageNid) {
    return AccessResult::neutral();
  }

  $allowlist = [
    // Diffy.
    '3.216.56.216',

    // Me.
    '22.222.22.222',
  ];

  $requestIP = \Drupal::request()->getClientIp();
  $isOnAllowlist = in_array($requestIP, $allowlist, TRUE);

  return AccessResult::allowedIf($isOnAllowlist);

}

Code snippet was provided by Felix Eve.

Also, make sure to exclude this page from your sitemap.xml as Google won’t be happy to index the page it doesn’t have access to (as advised by Kevin Reynen).

Related Articles

More guides on visual regression testing, QA automation, and keeping your site pixel-perfect as it changes.