Extending a base controller route with append, prepend or replace
Key Takeaway
server.append adds a step after the original route's middleware chain and cannot stop that chain, so the original middleware still runs. Replace the route with server.replace when the original middleware calls a web service or a third-party system, or does expensive work.
In SFRA, you change how a base controller route behaves without editing the app_storefront_base cartridge. You create a controller with the same name in your own cartridge and inherit the original with module.superModule and server.extend. Then you either append a step to an existing route or replace the route entirely. Your choice decides whether the original middleware still runs.
How to extend a base controller
Don't edit the app_storefront_base cartridge or the server module, because editing them voids the backward compatibility guarantee and makes upgrades harder. Instead, you build a controller in your own custom cartridge that inherits the original.
- In your custom cartridge, create a controller with the same file name and location as the base controller, for example
controllers/Product.js. - Place your custom cartridge to the left of the base cartridge on the cartridge path.
- In the controller, load the
servermodule withrequire('server')and get the original controller withmodule.superModule. - Call
server.extend(page), which inherits that server object along with all of its existing routes. - Call
server.appendorserver.replacefor each route you want to change. - Export the result with
module.exports = server.exports();.
var server = require('server');
var page = module.superModule;
server.extend(page);
// your server.append or server.replace calls go here
module.exports = server.exports();B2C Commerce searches the cartridge path from left to right. The first matching controller handles the request, so your controller is used instead of the base one.
B2C Commerce uses the first controller it finds with a matching name, without checking whether that controller contains the requested route. Calling a route that does not exist causes an error. Calling server.extend(page) keeps the inherited routes available from your controller, so the base routes you don't change can still be called.