Cert++
Close

SFRA req and res objects versus global request variables

Key Takeaway

In SFRA, read request data from req and send output with res instead of using B2C Commerce global variables. For example, a route reads query string parameters from req.querystring and returns JSON with res.json.

In SFRA (Storefront Reference Architecture), every controller route and middleware step gets a req object and a res object from the SFRA server module. The req object describes the incoming request. The res object sends output back to the shopper. SFRA code uses these two objects in place of the older habit of reading B2C Commerce global variables.

The server module and route arguments

The server module supplies objects with data from HTTP requests, responses and sessions. Every SFRA controller requires the server module with var server = require('server'). SFRA uses the server.req and server.res objects for request and response data. Global variables are still available, but using them in SFRA code is not recommended.

Each route function and middleware step takes three arguments in this exact order: req, res and next.

var server = require('server');

server.get('Show', function (req, res, next) {
    res.render('/home/homepage');
    next();
});

The Show route receives req, res and next in that order. The route calls res.render to output the /home/homepage template and then calls next().

Every middleware step must call next(), or the next function in the chain doesn't run. Calling next(new Error('...')) rejects the request instead.

B2C Commerce Developer Study Guide

Checklist progress

0/237Learned

Given a requirement, create and extend the functionality of a JavaScript controller that leverages models, decorators, factories, or helpers following API best practices, and renders a template or returns a JSON response

0/11

Prepare for the Exam

Play Today's Certle

Study Community

Ask questions and get the latest info from other B2C Commerce Developer studiers.