Sknoe / Notes
Build Add to Cart: A Backend-to-Frontend SFRA Journey
Build a tiny local cart, trace each browser-to-server handoff, then see how SFRA’s Cart-AddProduct route handles the same journey.
An Add to Cart button looks like one small piece of a product page. But when I started following SFRA requests, I learned that the button is only the first step: the browser sends product information, server-side code checks it and updates the basket, and the response tells the page what happened. If you only look at the button or only look at the controller, you miss how the two sides work together.
In the first SFRA guide, we followed a request into an ISML template. The Models and ViewModels guide then looks at how data is prepared for a page. This time we’ll follow an action in the other direction too: from the product page to the backend and back to an updated basket. You can run the small local version without a B2C Commerce account, then compare it with SFRA’s existing Cart-AddProduct route.
What we’ll build
The local lab has one product, a quantity field, an Add to Basket button, a Node.js server, and a basket kept separately for each browser session. The browser sends a POST request. The server checks the product ID and quantity, updates its basket, and returns JSON. The page reads that response to show the updated item count or an error.
This is a learning model, not a replacement for B2C Commerce. The local server uses an in-memory product and basket. SFRA uses Commerce product and basket APIs, and you’ll see how the route connects those platform pieces after trying the local flow.
1. Create the backend route
Create a folder and a public folder inside it. Save the following as server.js in the project folder. It uses only Node.js built-in modules, so there are no packages to install.
const http = require('node:http');const fs = require('node:fs');const path = require('node:path');const { randomUUID } = require('node:crypto');const port = 3000;const sessions = new Map();const product = { id: 'bag-001', name: 'Everyday Bag', price: 49, stock: 3 };function sendJson(res, status, data) {res.writeHead(status, {'Content-Type': 'application/json; charset=utf-8','Cache-Control': 'no-store'});res.end(JSON.stringify(data));}function getBasket(req, res) {const cookie = (req.headers.cookie || '').split(';').map(function (part) { return part.trim(); }).find(function (part) { return part.startsWith('sknoeDemoSession='); });let sessionId = cookie ? cookie.slice('sknoeDemoSession='.length) : '';let basket = sessions.get(sessionId);if (!basket) {sessionId = randomUUID();basket = { items: [] };sessions.set(sessionId, basket);res.setHeader('Set-Cookie','sknoeDemoSession=' + sessionId + '; HttpOnly; SameSite=Lax; Path=/');}return basket;}function basketView(basket) {return {itemCount: basket.items.reduce(function (total, item) {return total + item.quantity;}, 0),items: basket.items};}async function readJson(req) {const chunks = [];let size = 0;for await (const chunk of req) {size += chunk.length;if (size > 10000) {const error = new Error('Request too large');error.statusCode = 413;throw error;}chunks.push(chunk);}try {return JSON.parse(Buffer.concat(chunks).toString('utf8'));} catch (error) {const invalidJson = new Error('Invalid JSON');invalidJson.statusCode = 400;throw invalidJson;}}const server = http.createServer(async function (req, res) {if (req.method === 'GET' && req.url === '/') {res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });fs.createReadStream(path.join(__dirname, 'public', 'index.html')).pipe(res);return;}if (req.method === 'GET' && req.url === '/api/cart') {const basket = getBasket(req, res);return sendJson(res, 200, { cart: basketView(basket) });}if (req.method === 'POST' && req.url === '/api/cart') {let payload;try {payload = await readJson(req);} catch (error) {const status = error.statusCode === 413 ? 413 : 400;const message = status === 413? 'The request is too large.': 'Send a valid JSON request.';return sendJson(res, status, { message: message });}if (!payload || payload.productId !== product.id) {return sendJson(res, 404, { message: 'That product could not be found.' });}const quantity = Number(payload.quantity);if (!Number.isInteger(quantity) || quantity < 1) {return sendJson(res, 400, { message: 'Enter a whole-number quantity of at least 1.' });}const basket = getBasket(req, res);const line = basket.items.find(function (item) {return item.productId === product.id;});const nextQuantity = (line ? line.quantity : 0) + quantity;if (nextQuantity > product.stock) {return sendJson(res, 409, {message: 'Only ' + product.stock + ' are available in this demo.'});}if (line) {line.quantity = nextQuantity;} else {basket.items.push({productId: product.id,name: product.name,unitPrice: product.price,quantity: quantity});}return sendJson(res, 200, {message: product.name + ' added to your basket.',cart: basketView(basket)});}return sendJson(res, 404, { message: 'Page not found.' });});server.listen(port, function () {console.log('Open http://localhost:' + port);});
The route accepts JSON only at `/api/cart`. It gets the product ID and quantity from the request, looks up the product on the server, and changes the session basket only after the checks pass. The browser does not send a price; the server owns the product data. For this lab, the single known product stands in for the product catalog.
2. Build the product page
Create public/index.html. The form is the frontend. Its JavaScript sends the POST request without reloading the page, then updates the basket count using the returned JSON.
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Add to basket lab</title></head><body><main><h1>Everyday Bag</h1><p>Demo price: $49</p><form id="add-to-cart"><input type="hidden" name="productId" value="bag-001"><label for="quantity">Quantity</label><input id="quantity" name="quantity" type="number" min="1" value="1" required><button type="submit">Add to basket</button></form><p id="message" role="status" aria-live="polite"></p><h2>Basket (<span id="item-count">0</span>)</h2><ul id="basket-items"></ul></main><script>const form = document.querySelector('#add-to-cart');const message = document.querySelector('#message');const count = document.querySelector('#item-count');const items = document.querySelector('#basket-items');function renderCart(cart) {count.textContent = cart.itemCount;items.replaceChildren();cart.items.forEach(function (item) {const row = document.createElement('li');row.textContent = item.name + ' — ' + item.quantity + ' × $' + item.unitPrice;items.appendChild(row);});}async function loadCart() {const response = await fetch('/api/cart');const data = await response.json();renderCart(data.cart);}form.addEventListener('submit', async function (event) {event.preventDefault();message.textContent = 'Adding…';try {const response = await fetch('/api/cart', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({productId: form.elements.productId.value,quantity: Number(form.elements.quantity.value)})});const data = await response.json();message.textContent = data.message;if (response.ok) {renderCart(data.cart);}} catch (error) {message.textContent = 'Could not reach the server. Try again.';}});loadCart().catch(function () {message.textContent = 'Could not load the basket. Is the server running?';});</script></body></html>
3. Run it and follow one request
mkdir -p sfra-add-to-cart-lab/publiccd sfra-add-to-cart-lab# Save server.js here and index.html inside public/node server.js
Open `http://localhost:3000`. Add one bag, then add another. The browser’s mini basket count should change after each successful response. Try quantity 0 or a quantity that exceeds the demo stock to see an error returned by the server. Change the hidden product ID to an unknown value to see the not-found response.
Browser displays product
The page holds a product ID and a quantity selected by the shopper.
Frontend sends POST
Browser JavaScript sends the product ID and quantity to /api/cart.
Backend validates
The route checks the product and quantity against server-side data.
Basket changes
The server updates the basket associated with this browser session.
Backend returns JSON
The response reports success or an error and, on success, the updated basket.
Frontend updates page
The browser displays the message and new basket count from the response.
Notice where the product name and price come from. The browser submits an ID, but the server chooses the product data and unit price. If the server rejects the request, the frontend shows the message and leaves the displayed basket unchanged.
Under the hoodHow the demo remembers which basket is yours
Looking closer
When the browser first asks for /api/cart, the server creates a random session ID, stores a new basket in a Map, and sets an HttpOnly cookie. The browser sends that cookie on later same-origin requests. The server uses the ID to find the right basket, so two separate browser sessions get separate in-memory baskets. This demo loses all baskets when the Node process stops. Real SFRA does not store a shopper basket in a JavaScript Map: the platform manages basket objects and basket persistence. The local cookie example is for understanding the request handoff, not production session security.
How the same journey appears in SFRA
The local lab uses `/api/cart`; the standard SFRA route is `Cart-AddProduct`. Its POST request accepts form values such as `pid` and `quantity`, with options for products that need them. The base controller gets the shopper’s current basket, calls cart helper code to add the product, recalculates the basket when the addition succeeds, and returns JSON containing the result and updated cart information.
This is where the earlier SFRA articles connect. The controller receives the browser request; the basket and helper APIs do server-side work; a cart model shapes the response; and frontend JavaScript reads that response to update the page. The real route also supports cases this one-product lab leaves out, including options, product sets, bonus items, and Commerce-specific basket calculations.
You can study the route in the SFRA base cartridge, but don’t edit the base file for a storefront customization. To change behavior, use a custom cartridge and the project’s established extension pattern. Cartridge setup is a small prerequisite for deploying real SFRA code; it doesn’t need to block you from running the local lab first.
Debug it from the button to the basket
If clicking the button appears to do nothing, open your browser’s Network panel and submit again. Follow the request instead of guessing:
1. Did the browser send a POST to `/api/cart` (or `Cart-AddProduct` in SFRA)?
2. Does the request contain the product ID and quantity you expected?
3. What status and JSON response did the server return?
4. Did the backend add the item, or return a validation error?
5. Did the frontend read that response and update the message and count?
Where to go after your first full-stack feature
How SFRA Works: Controllers, pdict, res.render(), and ISML
Explains the page-rendering path
See how a browser request reaches a controller and how ISML returns HTML.
SFRA Models and ViewModels
Explains how backend data is shaped for the page
Follow how server-side data becomes a predictable object for rendering.
Controller middleware
Adds reusable steps around routes
Learn how shared checks and data preparation can run before route logic.
Cartridge paths
Control how custom code extends SFRA
Learn how a custom cartridge can customize the base storefront without editing its files.
You’ve now traced one feature across the full loop: the page sent an action, the server validated it and changed basket state, and the response gave the page enough information to show what happened. Once this path makes sense, variations, wishlists, and checkout have somewhere concrete to fit.
Did this click?
Tap the bulb if this explanation helped.
Further reading
- SFRA Cart.js controller source
- SFRA Cart route reference
- Build SFRA
- 20 Commerce Cloud Interview Questions and Answers
Understand the page-data flow
For the SFRA model and ViewModel work that prepares data before it reaches ISML, see SFRA Models and ViewModels: How Data Gets Ready for ISML.
Interview questions
What is SFRA and how does it differ from SiteGenesis?
SFRA is Salesforce B2C Commerce’s Storefront Reference Architecture. It uses JavaScript controller routes and middleware with cartridges, while the older SiteGenesis architecture is based on pipelines. This question was reported as asked in Commerce Cloud technical interviews by a contributor describing 13 interview screens.
What is a cartridge and how does the cartridge path work?
A cartridge packages storefront code such as controllers, models, templates, and scripts. The cartridge path is an ordered list that determines which implementation Commerce resolves first. This question was reported as asked in Commerce Cloud technical interviews by a contributor describing 13 interview screens.
In an SFRA add-to-cart request, what product information does Cart-AddProduct receive?
The standard route accepts a product ID and quantity, and it can also receive product options or related product data for more complex product types. The server must use those identifiers to resolve and validate Commerce data; it should not trust a price supplied by the browser.
Why should the product page update its basket count only after the server responds?
The server is responsible for validating the request and changing basket state. Updating the count optimistically before the response can show success even when the server rejects the product or quantity. The UI should render the confirmed response or an error.
How would you trace an Add to Cart button that appears to do nothing?
Inspect the browser Network panel, verify the POST URL and request fields, read the response status and JSON, trace the controller and basket helper result, then check whether frontend code handles the response and updates the page. Follow the value through each boundary instead of starting by changing the template.
Why is validating quantity only in the browser insufficient?
Browser-side checks improve the shopper experience but can be bypassed or altered. The backend must validate that quantity is a valid positive integer and enforce product and inventory rules before changing basket state.