Redirect after login

Sign up to bookmark this snippet
Components

Adding a redirect to hook_user_login() is a common mistake. You should never add the redirect there because redirecting users in that hook would stop other hook_user_login() implementations from being invoked. To properly redirect users to some page after they log in, you should add a custom submit handler to the user login form.

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

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

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