Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 28 ยท Practice and Review

SFCC Cheat Sheet

A quick Salesforce B2C Commerce developer reference: cartridge layout, controller pattern, ISML tags, dw classes, hook names, caching rules, logging and CLI commands.

This is a quick reference for everyday Salesforce B2C Commerce (SFCC) work. It does not teach; it reminds. Each block links to the lesson that explains the idea. The platform cannot run on this site, so all platform code is read-only. Two small runnable stand-ins at the end (a hooks.json linter and a cacheability advisor) let you practice the reasoning in plain JavaScript; they are not the Script API. Names and options change between releases, so confirm anything unusual in the documentation of the release you target. Entries marked "check" are the ones most likely to differ.

flowchart LR
    R["Request<br/>Cart-Show"] --> C["Controller route<br/>middleware + steps"]
    C --> M["Models and helpers<br/>dw.* Script API"]
    M --> T["ISML template<br/>or JSON"]
    T --> K["Page cache<br/>and CDN"]

The path of a storefront request, and where each part of this sheet applies.

Cartridge layout

TEXT
cartridges/
  plugin_gift/
    package.json                 // name, "hooks": "./hooks.json", "caches": "./caches.json"
    hooks.json
    caches.json
    steptypes.json               // custom job steps (check location in your layout)
    cartridge/
      plugin_gift.properties     // optional cartridge settings
      controllers/               // Cart.js, Checkout.js ...
      models/                    // plain-object models
      scripts/
        helpers/                 // pure logic, easy to test
        hooks/                   // hook implementations
        jobs/                    // job step functions
        services/                // service wrappers
      templates/
        default/                 // ISML templates
        resources/               // .properties message bundles
      forms/default/             // form definition XML
      static/default/            // compiled CSS, JS, images
      client/default/            // source JS and SCSS for the build
      experience/                // Page Designer components
    metadata/                    // import files (attributes, preferences)

Resources are found left to right on the site cartridge path; the first match wins (plugin_gift:app_brand:app_storefront_base). Overlay the base, never edit it. See Cartridges and the Cartridge Path.

Controller pattern

JavaScript
'use strict';

var server = require('server');
var csrfProtection = require('*/cartridge/scripts/middleware/csrf');
var consentTracking = require('*/cartridge/scripts/middleware/consentTracking');
var cache = require('*/cartridge/scripts/middleware/cache');

server.get('Show', consentTracking.consent, cache.applyDefaultCache, function (req, res, next) {
    var BasketMgr = require('dw/order/BasketMgr');
    var CartModel = require('*/cartridge/models/cart');

    var basket = BasketMgr.getCurrentBasket();
    res.render('cart/cart', { cart: basket ? new CartModel(basket) : null });
    next();
});

server.post('Add', csrfProtection.validateAjaxRequest, function (req, res, next) {
    var form = req.form;                 // posted fields
    res.json({ success: true });
    next();
});

module.exports = server.exports();
Piece Use
server.get, server.post Define a route; the second argument onward is the chain
server.append, server.prepend, server.replace Change an existing route (after server.extend(module.superModule))
req.querystring, req.form, req.httpMethod, req.currentCustomer, req.locale Request data
res.render(template, data), res.json(obj), res.redirect(url) Responses
res.setViewData(obj), res.getViewData() Merge data for the template or JSON
res.setStatusCode(n) Status code
this.on('route:BeforeComplete', fn), this.on('route:Complete', fn) Route events
next() Continue the chain; always call it unless you end the request

Middleware names above (csrf, consentTracking, cache) are the usual SFRA ones; check your base cartridge version for the exact list. Details: Controllers, Routes and Middleware.

Models and decorators

JavaScript
function productModel(product) {
    var model = Object.create(null);
    Object.defineProperty(model, 'id', { enumerable: true, value: product.ID });
    Object.defineProperty(model, 'name', { enumerable: true, value: product.name });
    return model;
}
module.exports = productModel;

Properties must be enumerable: true to appear in JSON.stringify and in loops. Extend a base module with var base = module.superModule;. See Models, Decorators and Helpers.

ISML tags

Tag Purpose
<isprint value="${x}" encoding="on" /> Output a value; encoded by default for the context
<isif condition="${...}">, <iselseif>, <iselse> Conditions
<isloop items="${list}" var="item" status="loopstate"> Loop (loopstate.first, .last, .count, .index)
<isset name="x" value="${...}" scope="page" /> Set a variable (page, request, session, pdict)
<isinclude template="path/to/file" /> Local include
<isinclude url="${URLUtils.url('Product-Tile')}" /> Remote include, its own request and cache rules
<isdecorate template="common/layout/page"> ... </isdecorate> Wrap content in a layout
<isreplace/> The spot in the layout where decorated content goes
<iscomment> ... </iscomment> Comment, not sent to the browser
<iscache type="relative" hour="24" /> Cache the page (check available attributes)
<iscache status="off" /> Do not cache this response
<isscript> ... </isscript> Inline script (avoid; keep logic in controllers and helpers)
<iscontent type="text/html" charset="UTF-8" /> Content type
<isstatus value="404" />, <isredirect location="..." /> Status and redirect
<isslot id="home-banner" context="global" description="..." /> Content slot

Messages and URLs inside templates:

HTML
<isprint value="${Resource.msg('cart.title', 'cart', 'Your cart')}" />
<a href="${URLUtils.url('Cart-Show')}">Cart</a>
<img src="${URLUtils.staticURL('/images/logo.svg')}" alt="" />

Never turn encoding off for user-controlled text. See ISML Templates.

Common Script API classes

Package Classes (require('dw/...'))
dw/system Site, Logger, Transaction, Status, HookMgr, CacheMgr, Request, Session
dw/catalog ProductMgr, CatalogMgr, ProductSearchModel, PriceBookMgr
dw/order BasketMgr, OrderMgr, Order, ShippingMgr, PaymentMgr, TaxMgr
dw/customer CustomerMgr, Customer, Profile
dw/object CustomObjectMgr
dw/svc LocalServiceRegistry
dw/web Resource, URLUtils, Form
dw/util Collection, ArrayList, HashMap, StringUtils, Calendar
dw/io File, FileWriter, FileReader, XMLStreamWriter
dw/campaign PromotionMgr
dw/content ContentMgr
JavaScript
var Transaction = require('dw/system/Transaction');
var Logger = require('dw/system/Logger');
var Site = require('dw/system/Site');

Transaction.wrap(function () { order.custom.flag = true; });   // writes need a transaction
Site.current.getCustomPreferenceValue('myPreference');          // site preference
Logger.getLogger('myfeature', 'MyCategory').error('Failed: {0}', message);

Persistent objects are written inside Transaction.wrap; unset custom attributes read as null. Collections returned by the platform are dw.util.Collection, not arrays; use .toArray() or iterate with .iterator(). Close search and query iterators. See The Script API and Common Classes.

Money and baskets

JavaScript
var BasketMgr = require('dw/order/BasketMgr');
var OrderMgr = require('dw/order/OrderMgr');

var basket = BasketMgr.getCurrentBasket();          // null if there is none
var order = OrderMgr.createOrder(basket);           // inside a transaction
OrderMgr.placeOrder(order);                         // after payment succeeded
OrderMgr.failOrder(order, true);                    // when payment fails

Totals use platform money types, not floats. See Basket, Checkout and Order Flow.

Hooks

Registration in package.json and hooks.json:

JSON
{
  "hooks": [
    { "name": "dw.order.calculate", "script": "./cartridge/scripts/hooks/calculate.js" },
    { "name": "dw.ocapi.shop.basket.afterPOST", "script": "./cartridge/scripts/hooks/basketHooks.js" }
  ]
}
Hook name (examples) Purpose
dw.order.calculate Recalculate the basket
dw.order.calculateShipping, dw.order.calculateTax Shipping and tax calculation
dw.order.createOrderNo Generate order numbers
app.payment.processor.<id> Payment processor Handle and Authorize
dw.ocapi.shop.<resource>.beforePOST, afterPOST, modifyGETResponse ... Shop API extension points
dw.system.request.onRequest, dw.system.request.onSession Request and session lifecycle
JavaScript
var HookMgr = require('dw/system/HookMgr');
if (HookMgr.hasHook('app.myfeature.notify')) {
    HookMgr.callHook('app.myfeature.notify', 'notify', payload);
}

Exact names and signatures differ by hook type; look them up before use. See Hooks and Extension Mechanisms.

Services

JavaScript
var LocalServiceRegistry = require('dw/svc/LocalServiceRegistry');

var svc = LocalServiceRegistry.createService('my.service', {
    createRequest: function (service, args) {
        service.setRequestMethod('POST');
        service.addHeader('Content-Type', 'application/json');
        return JSON.stringify(args);
    },
    parseResponse: function (service, response) { return JSON.parse(response.text); },
    mockCall: function () { return { statusCode: 200, statusMessage: 'OK', text: '{}' }; }
});

var result = svc.call({ id: 1 });
if (!result.ok) { /* result.status, result.error, result.errorMessage */ }

URL, credentials, timeout and circuit-breaker options live in Business Manager. See Service Framework and Third-Party Integrations.

Caching rules of thumb

Situation Do
Static content (images, CSS, JS) Long cache; version file names or paths
Product and category pages for guests Cache with a sensible time
Price or promotion-sensitive output Use the promotion-sensitive cache variants or a short time
Personal content (name, basket, wishlist) Do not cache in the shared page; use a remote include or a separate request
POST, forms, checkout steps Do not cache
Anything that depends on locale, currency or site It must be part of what makes the cache entry unique
Data your own scripts compute repeatedly A custom cache (CacheMgr.getCache(id)) with caches.json limits
JavaScript
var CacheMgr = require('dw/system/CacheMgr');
var cache = CacheMgr.getCache('myFeatureCache');          // declared in caches.json
var value = cache.get('key:' + locale, function () { return expensiveLookup(); });

SFRA middleware such as cache.applyDefaultCache sets default page cache times for a route; variants for promotion and inventory sensitivity exist, so check the middleware file in your base version. Page caches are cleared per site from Business Manager. See Caching and Performance.

Jobs

JSON
{
  "step-types": {
    "script-module-step": [
      {
        "@type-id": "custom.MyStep",
        "module": "int_my/cartridge/scripts/jobs/myStep.js",
        "function": "execute",
        "parameters": { "parameter": [] },
        "status-codes": { "status": [ { "@code": "OK", "description": "Done" } ] }
      }
    ]
  }
}

Keep steps idempotent, keep transactions short, and return a Status. See Jobs, Feeds and Import/Export.

Commands

Local project (SFRA-style package.json scripts; names vary by project):

Terminal
npm install
npm run compile:js
npm run compile:scss
npm run lint
npm test                    # unit tests
npm run uploadCartridge     # upload with the settings in dw.json

dw.json in the project root holds the connection settings (never commit secrets):

JSON
{
  "hostname": "zzzz-001.sandbox.us01.dx.commercecloud.salesforce.com",
  "username": "[email protected]",
  "password": "use an access key, not your login password",
  "code-version": "dev"
}

The sfcc-ci command line tool (check sfcc-ci --help for the commands your version supports):

Terminal
sfcc-ci client:auth <client-id> <client-secret>
sfcc-ci code:list <instance>
sfcc-ci code:deploy build/code.zip -i <instance>
sfcc-ci code:activate <version> -i <instance>
sfcc-ci instance:import data.zip -i <instance>
sfcc-ci job:run <job-id> -i <instance>
sfcc-ci sandbox:list

Setup details are in Setting Up Your Development Environment.

Logging and debugging

  • Logger.getLogger('prefix', 'Category') writes to files named after the prefix in the instance's log directory, retrievable in Business Manager or over WebDAV.
  • Levels are debug, info, warn and error; use placeholders instead of string concatenation. Enable debug level only temporarily.
  • Never log card data, passwords, tokens or full customer records.
  • Look at request logs and error logs first when a page returns a server error. See Testing, Debugging and Logging.

Common pitfalls

  • Editing app_storefront_base instead of overlaying it.
  • Forgetting next() at the end of a route step, which hangs the request.
  • Writing persistent objects outside Transaction.wrap.
  • Treating Collection objects as arrays, or leaving iterators open.
  • Reading custom attributes without a null guard.
  • Caching a page that contains personal or session-specific data.
  • Putting secrets in preferences, source code or logs.
  • Using encoding="off" on text that a shopper or merchant can edit.
  • Making slow service calls inside transactions or on every page view without timeouts.
  • Querying inside loops (one lookup per item) instead of fetching in bulk.

Two runnable stand-ins

JS A hooks.json linter

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

No output.

JS A cacheability advisor

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. Where do you register a hook implementation?

    package.json has a hooks entry pointing to hooks.json, which lists hook names and their scripts.
  2. 2. A controller step finishes its work but never calls next(). What happens?

    The route is a chain. A step that neither ends the response nor calls next() breaks it.
  3. 3. How should the mini cart, which shows the shopper's items, be served on a cached page?

    Shared cache entries are delivered to many visitors, so personal parts must be loaded separately.
  4. 4. Which statement about writing custom attributes is correct?

    Persistent writes need a transaction, which commits on success and rolls back on an exception.

Summary

  • Layout: cartridges with controllers, models, scripts, templates, static, client; the path decides which file wins.
  • Routes are chains: server.get/post, middleware, res.render/json, viewData, and append/prepend/replace for extension.
  • ISML encodes output by default; use remote includes for personal or separately cached parts.
  • Use Transaction.wrap for writes, close iterators, guard null attributes and keep secrets in service credentials.
  • Hooks are registered in hooks.json, services are configured in Business Manager, and jobs should be idempotent.
  • Cache by complete keys and never cache personal content in shared pages.

You have reached the end of the track. Revisit the Practice Exercises with Solutions to test yourself, or start again with What Is Salesforce B2C Commerce?.