How to redirect a user after login in Drupal the proper way

 

Automatically redirecting a user after logging into your Drupal website is a common requirement. In Drupal 7, you would probably have used hook_user_login() to perform this task, but with Drupal 8 came a more robust way to handle this. Our Drupal developers wrote this basic example code to show you how it's done.

Published on October 7, 2020

There are several stable contrib modules available that offer redirecting users - often as one of many functionalities. In some cases however, you might want to write your own module in order to precisely control what it does. Or perhaps you would like to combine this code with other specific requirements into a custom module.

Whatever your particular reason, here’s how redirect users the proper way in Drupal 8:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYCUSTOMMODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = 'MYCUSTOMMODULE_user_login_form_submit';
}

/**
 * Custom submit handler for the login form.
 */
function MYCUSTOMMODULE_user_login_form_submit($form, FormStateInterface $form_state) {
  $url = Url::fromRoute('/your/destination/path');
  $form_state->setRedirectUrl($url);
}

For Drupal 8 in particular, it is important to note that we no longer use hook_user_login(), because it would stop other implementations of that hook to be invoked. Instead, we’re adding a custom submit handler to the user login form.

Of course this is just a starting point. You could add certain conditions or redirect users to different paths depending on their user role. 

___

Hope this helps! Please don't be afraid to reach out if you need any help with your Drupal project. Our experts are always happy to help!

planet drupal
drupal 8
drupal 9