Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 28 ยท Controllers, Models and Templates

Controllers, Routes and Middleware

Write SFRA controllers: server.get and server.post, middleware like https and CSRF, res.render and res.json, viewData, redirects, route events and URLUtils, with a mini router to try.

Controllers are where an SFRA storefront decides what to do for a URL. A controller file groups related routes (Cart, Product, Account), and each route is a short chain of functions: some check conditions (middleware), and the last one prepares data and chooses a response. Most of your day-to-day work on a storefront happens here, so it is worth learning the patterns well.

You saw the big picture in SFRA Architecture and Request Flow. This lesson zooms in on writing routes: HTTP methods, middleware, responses, redirects, events and building URLs.

Controllers run only on the platform, so the real code below is read-only. The examples you can run are stand-ins: a mini router that mimics the middleware chain, the deferred rendering and a URL builder shaped like URLUtils.url. They simplify the real server module.

Defining routes

A controller starts by requiring the server module and ends by exporting its routes:

JavaScript
// Read-only: cartridge/controllers/Wishlist.js (illustrative)
'use strict';

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

server.get(
    'Show',
    server.middleware.https,
    consentTracking.consent,
    csrfProtection.generateToken,
    function (req, res, next) {
        var items = [];   // load from the platform here
        res.render('wishlist/list', { items: items });
        next();
    }
);

server.post(
    'AddProduct',
    server.middleware.https,
    csrfProtection.validateAjaxRequest,
    function (req, res, next) {
        var pid = req.form.pid;
        res.json({ success: Boolean(pid), pid: pid });
        next();
    }
);

module.exports = server.exports();
  • server.get and server.post bind a route name to an HTTP method. A request with the wrong method is rejected.
  • The arguments after the name are the steps. Everything except the last is usually middleware; the last is the "real" handler.
  • The route name plus the controller file name make the address: Wishlist-Show, Wishlist-AddProduct.

SFRA also has server.middleware.get and server.middleware.post to restrict methods for a route written another way, and server.middleware.include to mark a route as callable only as a remote include from a template.

The request and response objects

req gives you read access to what came in:

Property What it holds
req.querystring Query parameters, for example req.querystring.pid
req.form Posted form fields
req.httpMethod GET, POST and so on
req.currentCustomer A model of the current shopper (see Customers, Sessions and Profiles)
req.locale The locale information for the request
req.session A wrapper around the shopper's session

res is how you build the answer. The main methods are res.render(template, data), res.json(object), res.redirect(url), res.setViewData(object) and res.getViewData(). res.setStatusCode(code) and res.cacheExpiration(hours) are also common.

Remember that render and json describe the response and the platform produces it after the chain ends. That is why later steps and route:BeforeComplete handlers can still change the data.

Middleware

A middleware is just a step with the same signature as any other. It either calls next() to continue or ends the chain. SFRA ships useful ones:

Middleware Purpose
server.middleware.https Require a secure request, otherwise redirect
csrfProtection.generateToken Put a CSRF token into viewData for the template
csrfProtection.validateRequest / validateAjaxRequest Reject a POST without a valid token
consentTracking.consent Work out the tracking-consent state for the page
userLoggedIn.validateLoggedIn Redirect guests to the login page
cache.applyDefaultCache Add a standard page-cache lifetime

A middleware that rejects a request typically sets a redirect or a status and then calls next(new Error(...)), which stops the chain and keeps the remaining steps from running. Order matters: put https first, then authentication, then CSRF, then your handler. CSRF is covered in detail in Forms, Validation and CSRF.

flowchart LR
    R["Request"] --> M1["https"]
    M1 -->|"ok"| M2["csrf<br/>validate"]
    M2 -->|"ok"| H["Handler"]
    M1 -->|"insecure"| X1["Redirect to https"]
    M2 -->|"bad token"| X2["403 JSON"]
    H --> Out["res.render or res.json"]

A guard that fails ends the route; the handler only runs when every earlier step called next().

Responses: render, json and redirect

  • res.render('wishlist/list', data) renders an ISML template under templates/default/ and sends HTML. Pages use it.
  • res.json({ success: true }) sends JSON, which is how the storefront's front-end JavaScript talks to the server for AJAX calls such as add-to-cart.
  • res.redirect(URLUtils.url('Cart-Show')) sends a redirect. Call it before finishing, and do not also render.
JavaScript
// Read-only: redirect after a successful POST
var URLUtils = require('dw/web/URLUtils');

server.post('Remove', server.middleware.https, csrfProtection.validateRequest, function (req, res, next) {
    // ...remove the item...
    res.redirect(URLUtils.url('Wishlist-Show'));
    next();
});

URLUtils.url('Controller-Route', 'name', 'value') builds a link from an action name and name/value pairs, so you never hard-code the long /on/demandware.store/... form.

Events

The function that runs a step has an event emitter available as this. SFRA fires events such as route:Start, route:Step, route:BeforeComplete and route:Complete. route:BeforeComplete is the useful one: the response is about to be produced, so it is the last chance to adjust viewData.

JavaScript
// Read-only
this.on('route:BeforeComplete', function (req, res) {
    var viewData = res.getViewData();
    viewData.generatedAt = 'now';
    res.setViewData(viewData);
});

A mini router to experiment with

This stand-in implements methods, a middleware chain that stops on next(error), deferred rendering and route:BeforeComplete. It is not the real server module, but the flow is the same.

JS Mini router with middleware and events (stand-in)

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

No output.

Look at the first line of output: the handler set renderedBy inside a route:BeforeComplete listener, and it still appears in the rendered data, because the template is produced after that event. The plain-HTTP request never reaches the handler, and the wrong method gets a 405 before any step runs.

Building URLs

Hard-coded URLs break when the site ID, locale or URL rules change. The platform builds them for you with URLUtils. This stand-in shows the shape of URLUtils.url output and why name/value pairs must be encoded.

JS A URL builder shaped like URLUtils.url (stand-in)

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

No output.

Good habits

  • Keep controllers thin. Load data through models and helpers, not inline.
  • Return JSON from POST routes used by AJAX, and redirect after form posts that render pages.
  • Always require https and CSRF protection on routes that change state.
  • Prefer extending a base route over copying it (see Hooks and Extension Mechanisms for the other extension points).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a middleware that rejects a request usually do?

    Guards respond (redirect, 403 JSON) and stop the chain so the handler never runs.
  2. 2. Why can a route:BeforeComplete listener still change the rendered output?

    Rendering is deferred. Listeners run before the response is produced, so they can still add viewData.
  3. 3. Which is the right way to link to the cart in server code?

    URLUtils builds the correct site, locale and URL-rule aware address.
  4. 4. Which middleware order is sensible for a state-changing POST?

    Check the transport first, then the request's authenticity, and only then run the handler.

Summary

  • server.get and server.post bind a route name to an HTTP method; extra arguments are steps, usually middleware followed by the handler.
  • Built-in middleware covers https, CSRF, consent, login and caching; a failing guard stops the chain.
  • res.render, res.json and res.redirect describe the response, which the platform produces after the chain.
  • viewData and the route:BeforeComplete event let steps enrich the response late.
  • Build links with URLUtils.url('Controller-Route', ...) instead of hard-coding paths.

Next: Models, Decorators and Helpers