I have a site where I set a cookie when the user is visiting a specific content-type:
function THEME_preprocess_node(&$variables) {
if (isset($variables['node']) && $variables['node']->getType() == 'MYTYPE') {
// Store cookie with id of active node.
user_cookie_save(['THEME_location' => $variables['node']->get('nid')->getString()]);
}
}
Then if the user again is going to the frontpage, I would like to redirect him to the node referenced from the above cookie:
function THEME_preprocess(&$variables, $hook) {
$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
// Redirect the user to the selected node.
$cookies = \Drupal::request()->cookies->all();
if ($variables['is_front'] && isset($cookies['Drupal_visitor_THEME_location'])) {
$nid = $cookies['Drupal_visitor_THEME_location'];
$response = new RedirectResponse(\Drupal::url('entity.node.canonical', ['node' => $nid]));
$response->send();
}
}
The above works fine most of the time, but sometimes when loggin out from the backend and visiting the frontpage I only get a white screen and the page is completly dead. I know this is very vague but I cannot seem to reproduce this error by performing some specific steps. It just happens once in a while. If I then clear the cache everything seems to work as expected again? Can someone see what I am doing wrong here?