How to alter a route - Drupal 9

Components

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.

MY_MODULE.services.yml

services:
  MY_MODULE.route_subscriber:
    class: Drupal\MY_MODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

 src/Routing/RouteSubscriber.php

<?php

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 developer with over 10 years of experience in web, app, and AI solutions. He founded this website to share his expertise, provide useful resources, and contribute to the broader developer community.

AI Assistant