1

I have a module with an event subscribe that I use to redirect to an age verification page if a cookie is not set, and as long as the current request is not the age verification uri.

if(!isset($_COOKIE['age_gate_ok']) && $request != '/age-verification')
{
    $welcome = new\Symfony\Component\HttpFoundation\RedirectResponse("/age-verification");
    $welcome->send();
}

Problem: the event seems to listen once only, and that is when I use drush to clear cache. To further explain, I use clear site cache using drush and when I reload the page, it redirects me to the correct page(/age-verification) and then I pass the gate. However, if I open the inspector to clear cookies and refresh the page, the site does not redirect me to the age verification url.

How do I have to clear cache in order to have the age verification working?

4

You need to use a Trusted Redirect Response and properly set cache metadata for your response. This is mostly documented in an answer to a related question, Disabling Page Cache for Redirect Response. However, in your case, you'll need to manually build a CacheableMetadata object, so I'll show that here.

// Tell the browser not to cache the redirect by setting these headers.
$response_headers = [
  'Cache-Control' => 'no-cache, no-store, must-revalidate',
];

$response = new TrustedRedirectResponse($url, '302', $response_headers);
// We need to add cache metadata to the response so it can be properly cached by
// Drupal. If redirecting was based on a $node or entity, you could simply call
// $response->addCacheableDependency($node) and addCacheableDependency() would
// automagically pull the correct cache tags, contexts, etc from the object.
// Since your redirect depends on a cookie, you'll have to build a
// \Drupal\Core\Cache\CacheableMetadata object manually.
$cache_metadata = new CacheableMetadata();
// Since you just want to cache the response based on whether they have a cookie
// you can use just the cookies:NAME cache context.
$cache_metadata->setCacheContexts(['cookies:age_gate_ok']);
// Add the metadata to your response.
$response->addCacheableDependency($cache_metadata);

$event->setResponse($response);

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.