3 Steps to Enable Magento 2 Routing on Frontend and Admin
Want to simplify frontend and admin routing in Magento 2? Magento 2 routing directs URLs to the correct controllers and modules for efficient navigation.
In this tutorial, we will explore the key components and configuration steps of routing.
Key Takeaways
-
Magento routes request to specific controllers based on link structure.
-
Front-end and back-end requests are separated for a secure and organized structure.
-
Magento uses custom routes to handle API, CMS, and error management.
-
Follow the steps to create custom routes for front-end and admin areas.
-
Routing allows modularity and easier integration with external systems.
What is Magento 2 Routing?
Magento routing is the process of directing requests to specific controllers based on the URL structure.
Routing allows Magento to determine which module and controller should handle a particular request. It ensures that users see the correct content or functionality.
Routes are defined in a routes.xml file. Each route in Magento includes a router ID mapping links to modules. The routing system then directs requests to controllers that execute actions. These actions include rendering pages or processing data.
The modular setup enables:
-
Clean code organization
-
Efficient scalability
-
Flexibility
It supports both frontend and backend requests in Magento 2.
Key Components of Magento Routing
1. Routes Configuration (routes.xml)
-
Each module that needs custom routes has a routes.xml file. It is usually located in either the etc/frontend for front-end requests. It is located in etc/adminhtml for the admin requests directory within the module.
-
The file defines each route with unique identifiers, such as router ID and route ID. It links URLs to specific modules.
-
routes.xml tells Magento which module and which controller should handle a given URL structure.
2. Router ID
-
The router ID specifies the type of request or the application area. It helps Magento understand whether the front end or the admin panel should handle the route.
-
Common values for router IDs include:
-
standard for front-end routes
-
admin for admin panel routes
-
-
It helps in separating the routes. It ensures that the back-end and front-end links don’t conflict.
3. Route ID
-
The route ID is a unique identifier for each route in the application.
-
It defines part of the URL path and links to a specific module. It allows Magento to determine which module should handle the request.
-
When users access a link containing the route ID, Magento looks up the route in routes.xml to find the corresponding module and controller.
4. Front Name
-
The front name is part of the URL path specified in routes.xml. It enables Magento to recognize and process the route easily.
-
If frontName="custom," then accessing https://yourstore.com/custom/ will trigger Magento. It helps load this module’s controllers.
-
The front name acts as a custom link path. It makes the route more identifiable and SEO-friendly.
5. Controllers
-
Controllers are PHP classes within the Controller directory of each module. They handle specific actions based on the request.
-
The URL structure {module}/{controller}/{action} maps to a particular controller and method within the module.
-
Controllers contain the execute method. It is where the logic takes place for:
-
Processing requests
-
Rendering templates
-
Delivering responses (e.g., JSON)
-
How Does the Basic Routing Structure Work?
1. Request Handling Begins with the Front Controller
-
Every request to a Magento 2 store goes through a front controller (Magento\Framework\App\FrontController). It is responsible for receiving the URL and delegating it to the correct module.
-
The front controller is the first layer of routing. It identifies which area (front-end or admin) the request belongs to based on the link.
2. Reading the routes.xml File
-
Each module that defines custom routes has a routes.xml file in its etc/frontend or etc/adminhtml directory.
-
Magento checks the routes.xml files to match the link to the correct route configuration.
-
The route configuration includes the:
-
Router ID
-
Route ID
-
Front name
-
-
It defines which module and controller will handle the request.
3. Matching the Router ID
-
The router ID specifies the area. It is standard for the front end or admin for the back end.
-
Magento’s routing system uses this ID to determine if the front end or the admin panel should handle the request.
-
Magento ensures that front-end and back-end routes remain separate. It is by filtering requests this way.
4. Determining the Route ID and Front Name
-
The route ID and front name are specified in the routes.xml file. The front name forms part of the link. It tells Magento which module and controller to look for.
-
A URL like
https://yourstore.com/custom/index/view
would be mapped using:- Route ID: custom_route
- Front Name: custom
-
Magento uses this front name to locate the correct route ID. It helps identify the module handling the request.
5. Locating the Controller
-
After identifying the route ID and front name, Magento routes the request to the corresponding controller class in the specified module.
-
The controller is located in the module's controller directory and is further divided based on actions.
-
Each link structure follows the pattern {module}/{controller}/{action}, where:
-
module refers to the front name in routes.xml.
-
controller identifies the controller class.
-
action refers to the method within the controller.
-
6. Executing the Action Method
-
The controller class contains action methods, each of which is responsible for specific tasks.
-
Magento looks for an action that matches the last part of the link and calls its execute method.
-
The execute method contains the code that processes the request, such as:
-
Fetching data
-
Applying logic
-
Rendering a view
-
7. Generating the Response
-
The action method in the controller generates a response. It is typically done by rendering a page or returning data.
-
Responses can be:
-
HTML for web pages
-
JSON for AJAX requests
-
Even redirects to another link
-
-
It depends on the logic of the action method.
8. Returning the Response to the User
- Once the controller completes processing, the response is sent back. It is sent through the front controller to the user’s browser.
- The user then sees the page content, data, or result. It is based on the specific request they made.
Steps to Create a Custom Route on Frontend and Admin
Step 1: Create a frontend route
Create routes.xml in app/code/[Vendor]/[Module]/etc/frontend Folder add the following code:
<?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 frontName="helloworld" id="helloworld"\>
\<module name="\[Vendor\]\_\[Module\]"/\>
\</route\>
</router>
</config>
Step 2: Create an admin route
Create routes.xml in app/code/[Vendor]/[Module]/etc/adminhtml folder and add the following code:
<?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="admin">
\<route id="helloworld" frontName="helloworld"\>
\<module name="\[Vendor\]\_\[Module\]"/\>
\</route\>
</router>
</config>
Step 3: Use the route to rewrite the controller
Create routes.xml in app/code/[Vendor]/[Module]/etc/frontend Folder and add the following code:
<?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 frontName="helloworld" id="helloworld"\>
\<module name="\[Vendor\]\_\[Module\]"/\>
\</route\>
\<route id="account"\>
\<module name="\[Vendor\]\_\[Module\]" before="Magento\_Customer"/\>
\</route\>
</router>
</config>
Different Types of Routers in Magento 2
Router Type | Purpose | Key Features | Example Configuration | Example Use Case |
---|---|---|---|---|
1. Standard Router | It handles customer-facing front-end requests. | Routes are configured for customer-facing pages. URL patterns are mapped in routes.xml. It includes modular and flexible design. |
<router id="standard"><route id="custom_route" frontName="custom"><module name="Vendor_Module"/></route></router> | Product pages. Category pages. Custom modules. |
2. Admin Router | It processes Magento backend (admin panel) requests. | It routes for Magento admin panel functionality. It offers enhanced security and authentication. It is defined in routes.xml. |
<router id="admin"><route id="admin_route" frontName="admin_custom"><module name="Vendor_Module"/></route></router> | Order management. Catalog management in admin backend. |
3. API Router | It manages REST and SOAP API requests. | It handles external requests from third-party services. It supports OAuth tokens for authentication. It offers headless support. |
It is defined automatically for /rest and /soap endpoints. No additional routes.xml setup needed |
Integration with ERP, CRM, or other systems. |
4. Default Router | It offers a fallback for unhandled requests. | It serves as the default when no custom route matches. It often leads to a 404 error page if unmatched. It offers minimal config needed. |
It is managed internally by Magento’s core. It often handles default 404 routing. |
Unhandled routes, redirecting to default Magento pages |
5. CMS Router | It manages requests for CMS pages. | It handles links for static pages (e.g., About Us). It offers customization from the Magento admin panel. URL identifiers are used for matching. |
It is configured through the Magento admin under CMS pages. No routes.xml file is needed. |
About Us. Contact. Homepage. Other static pages |
6. Web API Router | It manages Web API data requests. | It is specialized for data exchange in REST and SOAP. It connects with mobile, headless apps. It maps APIs to module-specific methods. |
It offers automatic mapping through Magento’s Web API framework configuration. | REST and SOAP data requests for headless applications. |
What is The Purpose of Routing in Magento 2?
1. Connecting URLs to Modules and Controllers
-
Routing interprets incoming URLs. It connects them to the correct modules and controllers. These contain the business logic for each page or feature.
-
The connection allows Magento 2 to display the correct content. It also helps perform specific actions based on the URL structure.
2. Organizing Requests by Frontend and Backend Areas
-
Routing separates requests for front-end (customer-facing) and back-end (admin panel) sections. It makes the application secure and organized.
-
The separation prevents unintentional access to admin functionalities. It is done from the public-facing site.
3. Enabling Modularity and Customization
-
Routing allows each module to define its routes. It helps add, modify, or remove functionalities without altering the core system.
-
Developers can create custom routes for unique functionalities. It helps improve scalability and enables highly modular e-commerce solutions.
4. Supporting APIs for Integration
-
Routing supports REST and SOAP API routes. It allows the store to interact with:
-
Third-party applications
-
Mobile apps
-
Other external systems
-
-
The API support enables headless commerce setups and smooth integrations with CRM and ERP.
5. Handling CMS and Static Content
-
The routing system allows CMS (Content Management System) pages to be managed independently.
-
Static pages like “About Us” or “Contact” can be configured directly through the admin panel without additional code.
-
The feature gives store owners more control over static content management and SEO. It eliminates the need to involve developers.
6. Fallback and Error Management
-
Routing includes a default router. It handles requests not specifically matched by other routes.
-
The fallback ensures that even if a link doesn’t match a defined route. Magento can still handle the request gracefully. It often directs it to a 404 error page or default content.
FAQs
1. What is the purpose of the public function execute in Magento controllers?
The public function execute method in Magento controllers handles the main logic for processing URL requests. When a route is accessed, Magento calls this function to execute specific actions. These include rendering a view with PageFactory or fetching data.
2. How does the namespace work in Magento 2 modules?
Namespace organizes code under unique names. It ensures that classes like Magento\Framework\App\Action\Forward don’t conflict across modules. It helps manage dependencies and maintain clean code across frontcontroller actions and custom routes.
3. How can I create a custom route in Magento 2?
Define it in routes.xml under a module's etc directory. Then, link it to the appropriate controller. The route uses the frontcontroller to match the link. It directs it to the desired public function execute method for handling requests.
4. What role does layout handle play in Magento?
The layout handle is a key identifier in Magento that links link paths to layout XML files. It specifies the structure of a page. It controls the layout and content placement by matching the route to its designated XML filename. It includes use Magento\Framework\View\Result\PageFactory.
Summary
Magento 2 routing directs link requests to the appropriate modules and controllers. The tutorial uncovers the key aspects of routing, including:
-
routes.xml
maps links to modules by defining custom routers and route IDs. -
Controllers handle requests via action methods to execute logic.
-
Requests pass through the front controller to match links with modules.
-
Standard, admin, API, and web API routers each manage different request types.
Enhance your store’s performance and security with managed Magento hosting. It optimizes routing for smooth user experiences.