Cert++
Close

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.

  1. In your custom cartridge, create a controller with the same file name and location as the base controller, for example controllers/Product.js.
  2. Place your custom cartridge to the left of the base cartridge on the cartridge path.
  3. In the controller, load the server module with require('server') and get the original controller with module.superModule.
  4. Call server.extend(page), which inherits that server object along with all of its existing routes.
  5. Call server.append or server.replace for each route you want to change.
  6. 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.

B2C Commerce Developer Study Guide

Checklist progress

0/237Learned

Given a requirement, create and extend the functionality of a JavaScript controller that leverages models, decorators, factories, or helpers following API best practices, and renders a template or returns a JSON response

0/11

Prepare for the Exam

Play Today's Certle

Study Community

Ask questions and get the latest info from other B2C Commerce Developer studiers.