
A Magento 2 URL like /routing/index/index resolves in three parts: the frontName declared in etc/frontend/routes.xml picks your module, the second segment picks a Controller folder, and the third picks the action class. That class implements HttpGetActionInterface or HttpPostActionInterface and returns a result object: page, JSON, raw, redirect, forward, or layout.
That is the whole model in one paragraph, but most of the bugs we see in custom modules live in the details around it: a route declared in the wrong area, a POST action that silently fails the form key check, a JSON endpoint that ends up cached, or an admin controller that any logged-in user can open. This guide walks through each piece with the exact file names and class names, then covers what changes when the frontend is Hyva. If you want the broader picture of how we build and maintain custom modules, start with our Magento development services.
How a Magento 2 URL maps to a controller
Adobe’s routing documentation for Commerce PHP developers describes the standard URL format as store URL, optional store code, then front name, controller name, and action name. In practice:
https://example.com/routing/index/index
| | |
frontName folder class
- frontName comes from routes.xml and identifies the module.
- Controller name is a folder under your module’s Controller directory, for example Controller/Index.
- Action name is a PHP class inside that folder, for example Controller/Index/Index.php.
Anything after the action segment is parsed as key/value parameters, so /routing/index/view/id/42 gives you a request param named id with the value 42. If the controller or action segment is missing, Magento falls back to index, which is why /routing on its own lands on Controller/Index/Index.php.
Declaring a route in routes.xml
The file lives in either etc/frontend/routes.xml or etc/adminhtml/routes.xml, and the folder decides the area. A minimal storefront route looks like this:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="routing" frontName="routing">
<module name="ExampleCorp_RoutingExample"/>
</route>
</router>
</config>
Three attributes matter:
| Attribute | What it controls | Common mistake |
|---|---|---|
| router id | Which router handles the route: standard on the storefront, admin in the backend | Putting an admin route under standard, so it is public |
| route id | Internal name, and the first part of the layout handle | Assuming it must equal the frontName; it does not, though keeping them equal avoids confusion |
| frontName | The first URL segment after the base URL | Picking a frontName another module already uses, so one module wins silently |
The route id matters more than people expect. Adobe’s docs state that the layout file for a page is named routeId_controller_action.xml. With a route id of routing, controller Index, and action Index, your layout file is view/frontend/layout/routing_index_index.xml. If you rename the route id later, every layout handle for that module changes with it. Our guide to Magento 2 layout XML handles and containers covers how those handles are merged once the controller hands off to the page.
Overriding a core controller with before and after
You can add your module to an existing route and tell Magento to check it first:
<router id="standard">
<route id="customer">
<module name="ExampleCorp_RoutingExample" before="Magento_Customer"/>
</route>
</router>
With that in place, Adobe’s documentation notes that a class at Controller/Account/Login.php in your module is used in place of the core one. It works, but it replaces the whole action. If you only need to change behavior before or after execute(), a plugin is usually the smaller change, and it survives core updates to the rest of the class better.
The router list and the order Magento tries them
When a request comes in, the front controller walks a list of routers in sort order and stops at the first one that returns an action. Adobe documents the core storefront routers as:
| Router | Sort order | What it matches |
|---|---|---|
| robots | 10 | robots.txt |
| urlrewrite | 20 | URLs stored in the url_rewrite table (products, categories, CMS rewrites) |
| standard | 30 | frontName/controller/action routes from routes.xml |
| cms | 60 | CMS page identifiers |
| default | 100 | Nothing else matched, so the no-route (404) handler runs |
The admin area has its own short list: the admin router at 10 and a default router at 100.
This order explains a few real-world puzzles. A URL rewrite with the same path as one of your routes wins, because urlrewrite runs at 20 and standard at 30. A CMS page whose identifier matches your frontName never renders, because the standard router claims the request first.
Adding a custom router
When the URL shape does not fit frontName/controller/action, for example vanity paths like /brand/acme that come from your own table, you register a router in etc/frontend/di.xml:
<type name="Magento\Framework\App\RouterList">
<arguments>
<argument name="routerList" xsi:type="array">
<item name="brandRouter" xsi:type="array">
<item name="class" xsi:type="string">ExampleCorp\Brand\Controller\Router</item>
<item name="disable" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="string">40</item>
</item>
</argument>
</arguments>
</type>
The class implements Magento\Framework\App\RouterInterface and its match() method either returns null (not mine, try the next router) or rewrites the request’s module, controller, and action names and returns a Forward action from the ActionFactory. Adobe’s own example does exactly that with a sort order of 40, which slots it after the standard router and before CMS. Keep match() cheap: it runs on every request that reaches it, so a database lookup there should be indexed and, ideally, cached.
Writing the action class
Modern Magento 2 actions implement interfaces instead of extending a base class. Adobe’s current examples implement the HTTP method interfaces in Magento\Framework\App\Action directly:
<?php
declare(strict_types=1);
namespace ExampleCorp\RoutingExample\Controller\Index;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\PageFactory;
class Index implements HttpGetActionInterface
{
public function __construct(private PageFactory $pageFactory) {}
public function execute()
{
return $this->pageFactory->create();
}
}
The interface is not decoration. It tells Magento which HTTP methods the action accepts, and a request with any other method does not reach execute(). The ones you will use most:
| Interface | Accepts | Typical use |
|---|---|---|
| HttpGetActionInterface | GET (and HEAD) | Pages, read-only JSON endpoints |
| HttpPostActionInterface | POST | Form submissions, add-to-cart style mutations |
| HttpPutActionInterface | PUT | Rare on the storefront; mostly custom AJAX updates |
| HttpDeleteActionInterface | DELETE | Rare on the storefront |
A class can implement more than one. An action that renders a form on GET and processes it on POST can implement both, though splitting them into two classes keeps each one simpler to test.
You will still find older code that extends Magento\Framework\App\Action\Action and pulls the request and object manager from a Context object. It works, but the interface style keeps the constructor honest about what the class actually depends on. If the dependency injection side is new to you, our article on Magento 2 factories and proxies explains where PageFactory and the other result factories come from.
Returning the right result type
Every action returns a result object. Magento\Framework\Controller\ResultFactory defines a constant for each type, and you can either inject the specific factory or use ResultFactory with the constant. The ResultFactory source on GitHub is short and worth reading once.
| Result | ResultFactory constant | Dedicated factory | What it does |
|---|---|---|---|
| Page | TYPE_PAGE | Magento\Framework\View\Result\PageFactory | Applies layout handles and renders a full HTML page |
| Layout | TYPE_LAYOUT | Magento\Framework\View\Result\LayoutFactory | Renders layout output without the full page wrapper |
| JSON | TYPE_JSON | Magento\Framework\Controller\Result\JsonFactory | Encodes an array and sets Content-Type to application/json |
| Raw | TYPE_RAW | Magento\Framework\Controller\Result\RawFactory | Sends the body exactly as set, no Content-Type added |
| Redirect | TYPE_REDIRECT | Magento\Framework\Controller\Result\RedirectFactory | Sends a 302 so the browser requests a new URL |
| Forward | TYPE_FORWARD | Magento\Framework\Controller\Result\ForwardFactory | Runs another action internally; the URL does not change |
A JSON endpoint with the generic factory looks like this:
use Magento\Framework\Controller\ResultFactory;
public function execute()
{
$result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
return $result->setData(['ok' => true, 'items' => $this->loadItems()]);
}
Two habits save time. First, return a 404 for missing records with a forward to noroute (ForwardFactory, then forward(‘noroute’)) rather than a page that says “not found” with a 200 status. Second, use redirect for anything after a successful POST so a browser refresh does not resubmit the form. RedirectFactory’s setPath(‘//’) keeps you on the same route and controller without hardcoding the frontName.
POST actions and CSRF form key validation
Adobe’s routing docs note that a form key check applies to POST requests that are not AJAX. In practice this is the most common reason a new POST action “does nothing”: the request arrives without a valid form_key, validation fails, and the user is redirected back with no obvious error.
The fix is to send the form key, not to switch the check off. Every Magento form template should include it, and on Hyva you can read it in JavaScript with hyva.getFormKey() and add it to the body of a fetch call.
When you genuinely need different behavior, for example a webhook endpoint called by an external service that cannot know a form key, implement CsrfAwareActionInterface. It adds two methods:
- createCsrfValidationException() returns the exception (or null for the default) when validation fails.
- validateForCsrf() returns true to skip the check, false to fail it, or null to let Magento decide.
Returning true from validateForCsrf() means you own authentication for that endpoint. A webhook should verify a signature or shared secret in execute() before it touches any data. For machine-to-machine traffic, a proper REST endpoint is usually the better home anyway; our guide to Magento 2 custom REST API endpoints covers webapi.xml routes and ACL resources for that case.
Admin controllers: area, ACL, and the secret key
Admin routes go in etc/adminhtml/routes.xml under router id admin, and the URL is prefixed with the admin path rather than starting at the frontName. The action class extends Magento\Backend\App\Action, which brings in the authentication and authorization checks, and declares which ACL resource guards it:
class Index extends \Magento\Backend\App\Action implements HttpGetActionInterface
{
public const ADMIN_RESOURCE = 'ExampleCorp_RoutingExample::manage';
}
If you forget ADMIN_RESOURCE, the parent class falls back to a generic resource, and any admin role that can reach the dashboard may be able to open your page. Declare the resource in etc/acl.xml so it shows up in the role editor, and use the same id in menu.xml.
Admin URLs also carry a secret key by default (Stores, Configuration, Advanced, Admin, Add Secret Key to URLs). Build admin links with the backend URL builder, never by concatenating strings, or the key will be missing and the request will bounce to the dashboard.
What changes on a Hyva storefront
Routing and controllers are the same on Hyva as on Luma, because they are PHP and Hyva replaces the frontend layer. What changes is how the frontend talks to your actions.
- Pages. A page result still uses routeId_controller_action.xml, but the templates you add to it should be Hyva templates: Alpine.js and Tailwind instead of Knockout and RequireJS. Layout handles and containers behave the same.
- JSON endpoints. Many interactions that used to be Knockout components become small Alpine components that call a JSON action with fetch. That is a clean pattern, but remember that GET responses can be cached by full page cache or Varnish depending on headers, so customer-specific data belongs in customer data sections or in a POST, not in a cacheable GET.
- Partial updates. For HTML fragments instead of JSON, returning a layout result or using Alpine AJAX keeps the markup server-rendered. Our write-up on Alpine AJAX on Hyva shows that approach.
If you are planning a Luma to Hyva move with custom modules in the mix, the controllers usually survive untouched and the templates and JavaScript are where the work sits. That is the core of our Hyva development services.
Debugging a route that does not resolve
When a new route returns a 404, check these in order:
- Area. Is routes.xml in etc/frontend for a storefront route? A file in etc/ alone is not picked up for routing.
- Module enabled. Run bin/magento module:status and confirm the module is listed as enabled.
- Caches and generated code. Flush the config cache, and in production mode rerun setup:di:compile so new classes and constructor arguments are generated.
- Class path. The action must be at Controller/Folder/Action.php with a matching namespace. One wrong letter in a folder name means the standard router finds nothing.
- HTTP method. A POST to an action that only implements HttpGetActionInterface does not run.
- Router order. A URL rewrite or a custom router with a lower sort order may be claiming the path first.
Running the store in developer mode during this work helps, because exceptions are shown instead of logged.
Routing on other platforms
If your team also runs storefronts outside Magento, the mental model shifts. Shopify does not let you add server-side routes to the storefront at all, so custom endpoints live in apps and app proxies; see our Shopify development work for how we handle that. Shopware development uses Symfony routing with attributes on controller classes, which will feel familiar to anyone used to modern PHP. On BigCommerce development projects, custom server logic sits outside the platform behind its APIs. Magento’s routes.xml model is older, but it gives you the most direct control of the four.
FAQ
Does the route id have to match the frontName in routes.xml?
No. The frontName is the public URL segment and the route id is the internal name used in layout handles. Many core modules keep them equal, and doing the same in your own modules avoids confusion when you are searching for a layout file.
Why does my Magento POST controller redirect back without saving anything?
Almost always the form key. POST requests that are not AJAX are checked for a valid form_key, and a missing or stale key fails validation. Add the form key to the form or the fetch body. Only implement CsrfAwareActionInterface for endpoints that authenticate some other way, such as signed webhooks.
Should a Magento 2 controller extend Action or implement HttpGetActionInterface?
For new storefront code, implement the HTTP method interfaces and inject only what you need. Extending Magento\Framework\App\Action\Action still works and is common in older modules. Admin controllers are the exception: they extend Magento\Backend\App\Action to get authentication and the ADMIN_RESOURCE check.
How do I return a 404 from a Magento controller?
Return a forward result to noroute using ForwardFactory. The default router’s no-route handler then renders the store’s 404 page with a real 404 status, which is better for search engines than a 200 page that says the item was not found.
Do custom controllers work the same on Hyva?
Yes. Hyva changes the frontend templates and JavaScript, not PHP routing. Your routes.xml, actions, and result types behave exactly as they do on Luma. The difference is that frontend code calling your actions is usually Alpine.js with fetch, and templates in your page results should be written for Hyva.
Bemeir is a Brooklyn ecommerce agency that builds and maintains Magento, Adobe Commerce, and Hyva storefronts; you can read more about Bemeir, see our technology partners, or start a conversation at Bemeir.





