Skip to content

How to create custom route in Magento 2

This How to is more than 2 years old and may be outdated.

Report an error in the How to

Every time I create a new Magento module, I go through existing tutorials on the Internet because there are many files to create. The problem is that tutorials don't contain all the required files and that's why we need another tutorial. :) In today's how-to, we'll learn how to create Magento 2 module that displays custom template on custom route.

How to create custom route in Magento 2

URLs in Magento 2 contain 3 main parts:<front-name>/<controller-name>/<action-name>

If you're looking for more information about routing, take a look at official Magento 2 routing documentation.

Step 1

Create all required files

Create new folder app/code/Amazy/CustomRoute and add following files inside:





<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Amazy_CustomRoute" setup_version="0.0.1">


Inside this controller, you can add logic such as fetching specific products. If you don’t need render template inside Magento layout (e.g. you’re creating custom API route) you don’t need PageFactory and you can echo your json data directly inside execute method.

namespace Amazy\CustomRoute\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
	protected $_pageFactory;

	public function __construct(
		\Magento\Framework\App\Action\Context $context,
		\Magento\Framework\View\Result\PageFactory $pageFactory)
		$this->_pageFactory = $pageFactory;
		return parent::__construct($context);

	public function execute()
		return $this->_pageFactory->create();


<?xml version="1.0" ?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="test" id="test">
            <module name="Amazy_CustomRoute"/>



namespace Amazy\CustomRoute\Block;

class Index extends \Magento\Framework\View\Element\Template



<?xml version="1.0"?>
<page xmlns:xsi="" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Amazy\CustomRoute\Block\Index" name="test_index_index" template="Amazy_CustomRoute::index.phtml" />


<h3>Hello Daisy</h3>
Step 2

Activate module

Enable module by typing:

php bin/magento module:enable Amazy_CustomRoute
php bin/magento setup:upgrade
php bin/magento cache:clean
Step 3


Our custom route is now available! Check

Full code available on Github.

If you have any questions, you can always ask Daisy for help

Be the first to comment