SFRA controller route definition, middleware and module export
Key Takeaway
Every step in an SFRA route must call next(), or the functions after it never run, including the main function that renders the template. Every controller ends with module.exports = server.exports();, which registers its routes.
An SFRA controller is a JavaScript file in a cartridge's controllers folder that maps a storefront URL to server-side code. The controller registers named routes on the server module and runs a chain of middleware functions for each route. Every controller ends with module.exports = server.exports();, so B2C Commerce can match a request such as Home-Show to the right code. The design is conceptually similar to routing in NodeJS's Express.
What a controller file contains
Every SFRA controller starts with var server = require('server');. The server module provides routing for controllers. The server module lives in the global modules folder, so any controller can require it without a path. Requiring it returns an empty server object that you add routes to.
// Recipe.js in the controllers folder of a custom cartridge
var server = require('server');
server.get('Show', function (req, res, next) {
res.render('recipe/recipeDetails', { recipeId: req.querystring.id });
next();
});
module.exports = server.exports();The file must sit in the controllers folder, or B2C Commerce does not recognize it as a controller. The last line, module.exports = server.exports();, appears at the end of every controller. Calling server.exports() registers every function that uses server.get, server.post or server.use as a route.