How to alter a route - Drupal 9


Sometimes you have to alter a route that is defined by a contrib module or Drupal core. Don't hack the module and change the *.routing.yml file. That is a very bad idea because the next time you update the module those changes will be gone.

The best way to alter a route in Drupal 9 is to use a Route subscriber. In the following example, I had to change the allowed auth mechanism for the JWT auth issuer route.

    class: Drupal\MY_MODULE\Routing\RouteSubscriber
      - { name: event_subscriber }



namespace Drupal\MY_MODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

   * {@inheritdoc}
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('jwt_auth_issuer.jwt_auth_issuer_controller_generateToken')) {
      $route->setOption('_auth', ['basic_auth', 'email_basic_auth']);


Obviously, the $route object has a bunch of different useful methods like $route->setDefault() and $route->setRequirement(), so you can change anything you want.

About the Author

Goran Nikolovski is a senior web developer who loves working with Drupal, React, and React Native. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything? Get in touch.