I have a Drupal 8 site. And I have approximately 5 pages in a site.

For example if a user hits login from the contact-us page the user should not redirect anywhere, they should stay on same page. How can I accomplish this?


1 Answer 1


The way to solve this can be done by adding the destination parameter to the login link.

Whenever the user is navigating a page, you update the destination based on the current page.

This can be done by implementing the hook_link_alter as the following:

 * Implements hook_link_alter().
function custom_link_alter(&$variables) {
  $routes = [
  /* @var Drupal\Core\Url $url */
  $url = $variables['url'];

  if (!$url->isExternal() && $url->isRouted() && in_array($url->getRouteName(), $routes)) {
    // Get current path.
    $current = \Drupal::service('path.current')->getPath();
    $variables['options']['query']['destination'] = $current;

This works fine for login and also for logout links. So when user login/logout through menu link he will be redirected to the previous page.

One problem might face you with that is cache, Drupal will start caching the destination value and won't be updated when you move between pages.

You can solve this problem by implementing hook_preprocess_menu and add destination as cache contexts.

 * Implements hook_preprocess_HOOK().
function custom_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'account') {
    $variables['#cache']['contexts'][] = 'url.query_args:destination';
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, \Drupal::service('path.current')->getPath());

  • In the last line getPath() returns a string. When you don't provide a cacheable object, addCacheableDependency() adds automatically a cache max-age 0. So your code works because of this fallback, but is not optimal for performance. Such a solution is developed in this issue drupal.org/node/2582797, but there is much more code involved.
    – 4uk4
    Commented Nov 27, 2019 at 8:42

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