Drupal: how to redirect to a specific page after login

In this article, we'll look at two ways to redirect the user who is logging in, to a specific page in Drupal (version 9.5). First, Thesavvyfew alludes to a code solution that could be utilized:

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);
}

Then of course, there is the alternative solution and that is, installing a plugin. We recommend drupal/redirect_after_login as we've just tested it and it works. You can install this plugin as per the instructions, with the following command:

composer require 'drupal/redirect_after_login:^3.0'

We have noted over 10,000 installations of this plugin, which points to high quality implementation of this functionality.

The popularity of the plugin additionally demonstrates its usefulness.

Please login or register to post a comment.