Automatically redirecting a user after login in a Drupal project is a common requirement.
In Drupal 7, you'd probably have used hook_user_login() to handle this, but in Drupal 8/9 there's a more robust way to go about it. There are several contributed modules that offer this functionality, for example the "Redirect after login" module.
However, in some complex projects you need to write custom code to have precise control over what gets done. Whatever the reason, here's how to redirect users in Drupal 8/9:
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Implements hook_form_FORM_ID_alter().
*/
function MY_CUSTOM_MODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#submit'][] = 'MY_CUSTOM_MODULE_user_login_form_submit';
}
/**
* Custom submit handler for the login form.
*/
function MY_CUSTOM_MODULE_user_login_form_submit($form, FormStateInterface $form_state) {
$url = URL::fromUserInput('/custom/path');
$form_state->setRedirectUrl($url);
}
For Drupal 8/9 in particular, it's worth keeping in mind that we no longer use hook_user_login(), as it would stop other implementations of that hook from being invoked. Instead, we're adding a custom submit handler to the user login form.
Of course, this is just a starting point. You can add certain conditions or redirect users to different URLs based on their role or other parameters.