How can I add an age validator page? To access the site, all users (except the logged-in users) need to pass through an age gate. They can only leave the welcome page if they are 18 years or older.

I started by adding a session to my custom theme.theme file.

&lt;?php

function scottishleader_preprocess(&amp;$variables, $hook) {
  static $hooks;

  $route_name = \Drupal::routeMatch()-&gt;getRouteName();
  $response = new\Symfony\Component\HttpFoundation\RedirectResponse('/welcome');
  $session = \Drupal::request()-&gt;getSession();
  $session-&gt;set('initialSession', 'initial');

  if ($session-&gt;get('ageGate') == 'passed') {
    $session-&gt;remove('initialSession');
  }
  if ($route_name != 'agegate.route' &amp;&amp; $session-&gt;get('initialSession') == 'initial') {
    $response-&gt;send();
  } 
  if ($route_name == 'agegate.route' &amp;&amp; $session-&gt;get('ageGate') == 'passed') {
    $homeRoute = new\Symfony\Component\HttpFoundation\RedirectResponse('/');

    $homeRoute-&gt;send();
  }
}


Next, I created a custom module for the age gate and the routing.yml looks like the following.

agegate.route:
  path: '/welcome'
  defaults:
    _controller: '\Drupal\agegate\Controller\AgeGateController::content'
    _form: '\Drupal\agegate\Form\AgeGateForm'
  requirements:
    _permission: 'access content'


The AgeGateController class renders a form.

class AgeGateController extends ControllerBase {
  public function content(){
    return \Drupal::formBuilder()-&gt;getForm('Drupal\agegate\Form\AgeGateForm');
  }
}


It was all working fine until I realized that, if I am logged and I try to access the front page, I get redirected infinite times!

So, for some reason, my code only works on users that aren't logged-in.

How can I create this age gate functionality?
Implement the redirect in a module. Either in a kernel request subscriber, see this change record https://www.drupal.org/node/2013014 or in a kernel response subscriber, see https://git.drupalcode.org/project/age_verification/blob/8.x/src/EventSubscriber/pathGate.php.

The second example is from a contrib module you can try as it is. I don't have first-hand experience with this module, so I can't recommend or not recommend it, but this would be off-topic here anyway.