Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 28 ยท Extending the Platform

Hooks and Extension Mechanisms

Learn how to extend Salesforce B2C Commerce without forking it: hooks.json, HookMgr, calculate and OCAPI/SCAPI hooks, overriding versus extending, and plugin cartridges.

The golden rule of Commerce Cloud development is: do not edit the base cartridge. If you change app_storefront_base directly, every upgrade turns into a painful merge. Instead the platform offers several extension mechanisms that let your code run at well-defined moments, or replace a file, while the original stays untouched.

This lesson maps those mechanisms. The most important one is the hook: a named extension point (such as dw.order.calculate) that you implement in your own cartridge and register in a JSON file. Along the way you will see how hooks differ from route extension, how they power OCAPI and SCAPI customization, and how plugin cartridges combine them.

The extension toolbox

Mechanism What it does Typical use
Cartridge path override A file with the same path in an earlier cartridge wins Replace a template or a script completely
server.extend / append / prepend / replace Changes a controller route Add data to a page, add a middleware step
module.superModule Wrap or extend the same file from a later cartridge Add a decorator to a model
Hooks Run your function at a named platform event Basket calculation, payment, API customization

You learned the first three in Cartridges and the Cartridge Path and SFRA Architecture and Request Flow. A hook is different in kind: the platform itself (or a controller) asks "is anyone listening for this?" and calls whoever registered.

Registering a hook

A cartridge that implements hooks has two pieces. First, package.json points to a hooks file:

JSON
{
  "name": "int_delivery",
  "version": "1.0.0",
  "hooks": "./hooks.json"
}

Second, hooks.json lists extension points and the script that implements each one:

JSON
{
  "hooks": [
    {
      "name": "dw.order.calculate",
      "script": "./cartridge/scripts/hooks/calculate.js"
    },
    {
      "name": "dw.ocapi.shop.basket.beforePOST",
      "script": "./cartridge/scripts/hooks/basketRules.js"
    }
  ]
}

The script exports functions named after the method of the extension point. For dw.order.calculate the platform defines the method calculate, so the script looks like this:

JavaScript
// cartridge/scripts/hooks/calculate.js (read-only: needs the real platform)
'use strict';

var Status = require('dw/system/Status');

exports.calculate = function (basket) {
    // 1. recalculate line item prices, 2. shipping, 3. promotions, 4. tax, 5. totals
    // ...
    return new Status(Status.OK);
};

For the cartridge to be active, it must be on the site's cartridge path (hooks of cartridges that are not on the path are ignored). After you upload the cartridge, activate the code version as usual.

Where do the hook names come from?

Extension points are defined by the platform, and every name has a fixed set of methods. A few you will meet:

  • dw.order.calculate: method calculate(basket). The platform default is implemented by the base cartridge's calculation scripts, and SFRA's CartModel and checkout call HookMgr.callHook('dw.order.calculate', 'calculate', basket) after any basket change. Related points cover shipping and tax (dw.order.calculateShipping, dw.order.calculateTax).
  • dw.order.payment.authorize and related payment hooks: how a payment instrument is authorized. The base cartridge ships a processor-specific hook per payment method.
  • dw.system.request.onSession and dw.system.request.onRequest: run at the start of a session or of each request. Use them sparingly: they run on every request, so slow code here slows the whole shop.
  • dw.ocapi.shop.* and dw.ocapi.data.*: before/after/modify hooks for the Open Commerce API, described below.

Always check the current Script API documentation for exact names and signatures; a typo does not fail at upload, it just means your hook is never called.

Calling hooks: HookMgr

The platform calls system hooks for you. For your own extension points you use dw.system.HookMgr:

JavaScript
var HookMgr = require('dw/system/HookMgr');

if (HookMgr.hasHook('app.delivery.estimate')) {
    var estimate = HookMgr.callHook('app.delivery.estimate', 'estimate', product, postalCode);
}

hasHook(extensionPoint) tells you whether at least one cartridge registered it, and callHook(extensionPoint, method, ...args) invokes the function and returns what it returns. If no hook is registered, callHook returns undefined rather than failing. That makes hooks a good way to build optional, replaceable behaviour: the base code works alone, and a project or plugin cartridge supplies the specialised version.

Custom hook names use your own prefix (app., int. or your company name) so they never clash with the dw. namespace, which belongs to the platform.

Hooks for OCAPI and SCAPI

APIs often need small rules the standard endpoint does not offer: reject a basket with too many items, add a computed field to the product response, log an order submission. The hooks dw.ocapi.shop.<resource>.<phase> solve this. The phases are:

  • beforePOST, beforePUT, beforeGET, ...: run before the platform handles the request; a returned Status with an error code stops it.
  • afterPOST and friends: run after the main work, in the same transaction for write calls.
  • modifyGETResponse, modifyPOSTResponse, ...: run just before the response is sent; you can add fields (to document types with custom attributes) or adjust the response.
JavaScript
// basketRules.js (read-only)
'use strict';

var Status = require('dw/system/Status');

exports.beforePOST = function (basket) {
    if (basket.productLineItems.length > 50) {
        return new Status(Status.ERROR, 'BASKET_TOO_LARGE', 'Too many items in one basket.');
    }
    return new Status(Status.OK);
};

Many Shopper API (SCAPI) calls reuse the same dw.ocapi.shop.* hooks, so a rule written once covers both APIs for the endpoints that support it. Whether a given SCAPI endpoint runs a given hook is documented per endpoint, so check before you depend on it. The APIs themselves are the subject of OCAPI and SCAPI.

Two warnings for API hooks. They run inside the request budget, so avoid remote calls there (or use a service with a short timeout, see Service Framework and Third-Party Integrations). And a hook that throws turns a harmless API call into an error for the client, so catch what you can and return a Status.

flowchart LR
    C["API client"] --> P["Platform handler"]
    P --> B["beforePOST hook<br/>(validate)"]
    B -->|"Status.OK"| M["Main processing"]
    B -->|"Status.ERROR"| E["Error response"]
    M --> A["afterPOST hook"]
    A --> R["modifyPOSTResponse hook"]
    R --> O["Response"]

The phases of an OCAPI write call: validate, do the work, then adjust the response.

Overriding or extending?

When you need to change behaviour, ask in this order:

  1. Is there a hook? Use it. It is the most stable contract.
  2. Is it a controller route? Use server.append, server.prepend or server.extend, which keep the base code in use.
  3. Is it a model or script? Wrap it with module.superModule and decorate the result.
  4. Is it a template? Override it by path in your cartridge, or better, add a small include so only a fragment differs.
  5. Replace the whole file only when nothing smaller works. Every full copy is a future merge.

The larger a copy of base code in your cartridge, the more it costs at upgrade time. Plugin cartridges made by Salesforce and partners follow the same discipline.

Plugin cartridge patterns

A plugin cartridge is a self-contained feature (wishlist, gift registry, a payment integration). Good plugins share a structure:

  • A name with a prefix: plugin_ for generic features, int_ for integrations with an external system, app_ for storefront layers.
  • Placement on the cartridge path to the left of the base cartridge, so its files and routes win: plugin_delivery:app_custom:app_storefront_base.
  • Only the files that differ: controllers that call server.extend(module.superModule), new templates, a hooks.json, and metadata XML.
  • A package.json hooks entry, so installation is "put the cartridge on the path and import the metadata".
  • Separate business code from glue: scripts/ holds testable logic and the hook file only forwards to it.

Because plugins are on the path in order, the order matters. If two plugins extend the same route, they chain through module.superModule from left to right. If two cartridges register the same hook, check the behaviour for that extension point in the current documentation and test it on a sandbox instead of assuming; do not build designs that depend on which one wins.

Live stand-ins

The first stand-in is a small hook manager. It follows the same ideas as HookMgr (register by name, hasHook, callHook, undefined when nothing is registered) but is only a model. As a policy it calls the first registration in cartridge-path order; the real platform's rules for several registrations of the same point should be taken from its documentation.

JS A hook manager with a cartridge path

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in imitates before/after/modify phases of an API call, including a hook that blocks a request by returning an error status.

JS before, after and modify phases of an API call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file tells the platform which script implements which extension point?

    The cartridge's package.json has a hooks entry that points to hooks.json, which lists name and script for each hook.
  2. 2. A cartridge registers dw.order.calculate but the hook is never called. What is the most likely cause?

    Hooks of cartridges that are not on the cartridge path of the current site are ignored. A misspelled hook name behaves the same way.
  3. 3. What does HookMgr.callHook return when no cartridge has registered the extension point?

    callHook returns undefined when nothing is registered, which is why code often checks hasHook first.
  4. 4. You want to reject baskets with too many items in the Shopper API. Which hook fits best?

    A before hook runs before the main processing and can stop the request by returning an error Status.

Summary

  • Prefer extension over modification: hooks, server.extend/append/prepend, module.superModule, then template overrides, and full file copies last.
  • A hook is a named extension point; the cartridge registers it in hooks.json (referenced from package.json) and exports a function named after the method.
  • HookMgr.hasHook and callHook let your own code offer optional extension points.
  • dw.ocapi.shop.* before, after and modify hooks add rules and fields to API calls; keep them fast and return a Status.
  • Plugin cartridges are small, prefixed, ordered to the left of the base cartridge, and keep business logic out of the glue.

Next: calling other systems from those hooks safely in Service Framework and Third-Party Integrations.