When building sites, many client wants users to get redirected to particular page (like Site Home Page) or page based on User Roles. Today we'll see how we can redirect user after login to particular page.

NOTE: I've defined my own custom page using [MODULENAME].routing.yml named as "custom.redirect_callback", which we'll be using for redirecting user.

<?php
/**
 * Implements hook_form_alter().
 */
function [MODULENAME]_form_alter(&$form, \Drupal\Core\Form\FormStateInterface\FormStateInterface $form_state, $form_id) {
  switch (
$form_id) {
   
// Alter login form and add own custom submit handler.
   
case 'user_login_form':
     
$form['#submit'][] = '_[MODULENAME]_user_login_form_submit';
      break;
  }
}

/**
 * Custom submit handler for login form.
 */
function _[MODULENAME]_user_login_form_submit($form, FormStateInterface $form_state) {
 
// Set redirect to login form.
 
$form_state->setRedirect('custom.redirect_callback');
}
?>

Like Drupal7 we can't set $form_state['redirect'] directly, because $form_state is now class object. Checkout FormState::setRedirect for further details.

Reference: