Hikmadh Commerce| Ecommerce Development Consulting | Magento Development and Consulting Service


How to Add a Custom Router in Magento 2

 
Introduction

Magento 2 is a powerful eCommerce platform known for its modular architecture and customization capabilities. While working on custom functionalities, you may come across a scenario where the default routing system doesn’t meet your needs — this is where custom routers come into play.

In this article, we’ll walk through the process of creating a custom router in Magento 2 — explaining each step from scratch. By the end, you’ll be able to intercept any URL and route it to a controller of your choice, dynamically and cleanly.

 

What is a Router in Magento 2?

A router in Magento 2 is responsible for matching incoming HTTP requests to specific controllers and actions. Magento uses different routers like standard, admin, cms, etc., to map URLs.

However, sometimes, you need to define a custom route that doesn’t follow Magento’s typical URL pattern — for example, to load a page like /video-streaming or intercept URLs dynamically for A/B testing, microsites, or special campaigns.

 

Use Case for Custom Routers
  • Custom landing pages (e.g., /video, /landing-page)

  • SEO-friendly routing outside the default module/controller/action structure

  • Injecting parameters before routing to the controller

  • Dynamic route handling based on custom logic

Steps to Add a Custom Router in Magento 2

We’ll use Hikmadh_Customize as the module name for this tutorial. Replace Hikmadh and Customize with your own vendor/module names as needed.

 

Step 1: Create Module Declaration Files

Create the following files to declare your module:

registration.php

app/code/Hikmadh/Customize/registration.php

				
					<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Hikmadh_Customize',
    __DIR__
);

				
			

 

module.xml

app/code/Hikmadh/Customize/etc/module.xml

				
					<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Hikmadh_Customize" setup_version="1.0.0" />
</config>

				
			

 

Step 2: Define Your Custom Router in di.xml

Create di.xml under the frontend scope:

app/code/Hikmadh/Customize/etc/frontend/di.xml

				
					<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\App\RouterList">
        <arguments>
            <argument name="routerList" xsi:type="array">
                <item name="customRoute" xsi:type="array">
                    <item name="class" xsi:type="string">Hikmadh\Customize\Controller\Router</item>
                    <item name="disable" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">40</item>
                </item>
            </argument>
        </arguments>
    </type>
</config>

				
			

 

Step 3: Create the Router Class

app/code/Hikmadh/Customize/Controller/Router.php

				
					<?php
declare(strict_types=1);

namespace Hikmadh\Customize\Controller;

use Magento\Framework\App\Action\Forward;
use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\RouterInterface;

class Router implements RouterInterface
{
    private $actionFactory;
    private $response;

    public function __construct(
        ActionFactory $actionFactory,
        ResponseInterface $response
    ) {
        $this->actionFactory = $actionFactory;
        $this->response = $response;
    }

    public function match(RequestInterface $request): ?ActionInterface
    {
        $identifier = trim($request->getPathInfo(), '/');
        if (strpos($identifier, 'video') !== false) {
            $request->setModuleName('hikmadh');
            $request->setControllerName('index');
            $request->setActionName('index');
            $request->setParams([
                'first_param' => 'first_value',
                'second_param' => 'second_value'
            ]);
            return $this->actionFactory->create(Forward::class, ['request' => $request]);
        }
        return null;
    }
}

				
			

 

Step 4: Add Route Declaration

app/code/Hikmadh/Customize/etc/frontend/routes.xml

				
					console.log( 'Code is Poetry' );<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="hikmadh" frontName="hikmadh">
            <module name="Hikmadh_Customize"/>
        </route>
    </router>
</config>

				
			

 

Step 5: Create the Controller Class

app/code/Hikmadh/Customize/Controller/Index/Index.php

				
					<?php
declare(strict_types=1);

namespace Hikmadh\Customize\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;

class Index implements HttpGetActionInterface
{
    private $pageFactory;
    private $request;

    public function __construct(
        PageFactory $pageFactory,
        RequestInterface $request
    ) {
        $this->pageFactory = $pageFactory;
        $this->request = $request;
    }

    public function execute()
    {
        $firstParam = $this->request->getParam('first_param');
        $secondParam = $this->request->getParam('second_param');
        return $this->pageFactory->create();
    }
}
?>
				
			

 

Step 6: Create Layout File for Page Title

app/code/Hikmadh/Customize/view/frontend/layout/hikmadh_index_index.xml

				
					<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="page.main.title">
            <action method="setPageTitle">
                <argument translate="true" name="title" xsi:type="string">Custom Router Active - Hikmadh Page</argument>
            </action>
        </referenceBlock>
    </body>
</page>

				
			

 

Step 7: Enable and Test the Module

Run the following commands:

				
					php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush
				
			

Visit yourdomain.com/video in the browser. If everything is correct, you’ll be redirected to the controller and see your custom page.

Conclusion

Adding a custom router in Magento 2 allows developers to handle specific URL patterns and route them to custom logic, offering more flexibility beyond default Magento routing. This approach is especially useful for SEO-friendly URLs, custom landing pages, or dynamic content. By following the proper module structure and configurations, you can implement a clean, maintainable routing solution tailored to your project needs. It’s a powerful technique every Magento developer should have in their toolkit.