Module loading practices in SFRA controllers
Key Takeaway
In an SFRA controller, require non-API helper modules inside the route functions that use them, not at the top of the file. Top-level require() calls run on every request, even when the route doesn't need the module.
In SFRA, controllers and scripts are CommonJS modules that load other code with require(). Where you call require() decides how much code the server loads on each request. The path you pass to require() decides which file it loads from the cartridge stack. The core best practice is to require a module only where it's needed, in the narrowest scope that works.
SFRA modules and controllers
SFRA controllers and scripts follow the Modules 1.1.1 CommonJS specification. A module is a .ds or .js file. Several controllers can reuse the same module, so modules are how controllers share functionality.
Module files live in a cartridge's scripts folder or in the special modules folder. The modules folder is a peer of the cartridge folders and holds globally shared modules, such as third-party modules. You can require anything in the modules folder or the TopLevel package without a path.
Every SFRA controller requires the server module, which sits in the global modules folder. Every SFRA controller also ends by exporting its routes:
var server = require('server');
// ... route definitions ...
module.exports = server.exports();The first line loads the server module without a path because it lives in the modules folder. The last line calls server.exports(), which registers the controller's routes.
Don't edit the server module, because editing it voids the backward compatibility guarantee and support. To customize its behavior, create your own module in the modules folder, require the server module functions there, and extend them.