How to redirect a user on login? I have a registration form, when submitted, the user gets logged in automatically.

I want to redirect the users to a specific page on login. Whether they are logged in using the login form or through the registration form.

I used the following code first,

function yourmodule_user_login($account) {
  // We want to redirect user on login.
  $response = new RedirectResponse("yourpath");
  $response-&gt;send();
  return;
}


This is not working because it's called before submit handlers so this would prevent them from being called.

Then I added a custom submit handler to the login form and redirect the users in that submit handler.

$form_state-&gt;setRedirect('mymodule.mypage');


This works fine only when the user logged in using the login form but not working for the registration form. When I use a custom submit handler for the registration and redirect the user there, I think at that time the user is not logged when the redirection occure.

Is there any other method to redirect the users on login through code?
Subscribe to the UserLogin event like below:

in yourmodule/src/Event/UserLoginEvent:

&lt;?php

namespace Drupal\yourmodule\Event;

use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * Event that is fired when a user logs in.
 */
class UserLoginEvent extends Event {

  const EVENT_NAME = 'yourmodule_user_login';

  /**
   * The user account.
   *
   * @var \Drupal\user\UserInterface
   */
  public $account;

  /**
   * Constructs the object.
   *
   * @param \Drupal\user\UserInterface $account
   *   The account of the user logged in.
   */
  public function __construct(UserInterface $account) {
    $this-&gt;account = $account;
  }

}


in yourmodule/src/UserLoginSubscriber.php:

&lt;?php

namespace Drupal\yourmodule\EventSubscriber;

use Drupal\yourmodule\Event\UserLoginEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class UserLoginSubscriber.
 *
 * @package Drupal\yourmodule\EventSubscriber
 */
class UserLoginSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      // Static class constant =&gt; method on this class.
      UserLoginEvent::EVENT_NAME =&gt; 'onUserLogin',
    ];
  }

  /**
   * React to the user login event dispatched.
   *
   * @param \Drupal\yourmodule\Event\UserLoginEvent $event
   *   Dat event object yo.
   */
  public function onUserLogin(UserLoginEvent $event) {
    $response = new RedirectResponse("yourpath");
    $response-&gt;send();
    return;
  }

}