sfra-controllers.mdcā¢13.8 kB
---
description: Enhanced SFRA controller development patterns and best practices with 26+ SFRA documents
globs: cartridges/**/controllers/*.js
alwaysApply: false
---
# Enhanced SFRA Controller Development
Use this rule when creating or modifying SFRA controllers. Now with access to 26+ SFRA documents and smart categorization.
## š Enhanced MCP Tools Sequence
**BEFORE writing ANY SFRA controller code:**
### Phase 1: Explore SFRA Architecture
1. `mcp_sfcc-dev_get_sfra_categories` - Discover all 7 SFRA documentation categories
2. `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "core" - Get core SFRA classes
3. `mcp_sfcc-dev_get_best_practice_guide` with guideName: "sfra_controllers" - Get comprehensive controller patterns
### Phase 2: Research Specific Functionality
4. `mcp_sfcc-dev_get_sfra_document` with documentName: "server" - Server class methods and routing
5. `mcp_sfcc-dev_get_sfra_document` with documentName: "request" - Request object capabilities
6. `mcp_sfcc-dev_get_sfra_document` with documentName: "response" - Response object methods
### Phase 3: Model-Specific Research (based on controller type)
**For Product Controllers:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "product"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "product-full"
**For Cart/Checkout Controllers:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "order"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "cart"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "billing"
**For Customer Controllers:**
- `mcp_sfcc-dev_get_sfra_documents_by_category` with category: "customer"
- `mcp_sfcc-dev_get_sfra_document` with documentName: "account"
### Phase 4: Security and Advanced Features
7. `mcp_sfcc-dev_search_best_practices` with query: "security" - Security patterns
8. `mcp_sfcc-dev_search_sfra_documentation` with query: [specific functionality] - Find relevant patterns
## š SFRA Documentation Categories (26+ documents)
### Available Categories:
- **Core** (5 docs): server, request, response, querystring, render
- **Product** (5 docs): product-full, product-bundle, product-tile, product-search, product-line-items
- **Order** (6 docs): cart, order, billing, shipping, payment, totals
- **Customer** (2 docs): account, address
- **Pricing** (3 docs): price-default, price-range, price-tiered
- **Store** (2 docs): store, stores
- **Other** (3+ docs): categories, content, locale
## MCP-Enhanced Development Workflows
### Workflow 1: Product Controller Development
```
1. mcp_sfcc-dev_get_sfra_documents_by_category with category: "core"
2. mcp_sfcc-dev_get_sfra_documents_by_category with category: "product"
3. mcp_sfcc-dev_get_sfra_document with documentName: "product-full"
4. mcp_sfcc-dev_search_sfra_documentation with query: "variation"
5. mcp_sfcc-dev_get_best_practice_guide with guideName: "sfra_controllers"
```
### Workflow 2: Cart/Checkout Controller Development
```
1. mcp_sfcc-dev_get_sfra_documents_by_category with category: "core"
2. mcp_sfcc-dev_get_sfra_documents_by_category with category: "order"
3. mcp_sfcc-dev_get_sfra_document with documentName: "cart"
4. mcp_sfcc-dev_get_sfra_document with documentName: "billing"
5. mcp_sfcc-dev_search_sfra_documentation with query: "payment"
```
### Workflow 3: Customer Management Controller Development
```
1. mcp_sfcc-dev_get_sfra_documents_by_category with category: "core"
2. mcp_sfcc-dev_get_sfra_documents_by_category with category: "customer"
3. mcp_sfcc-dev_get_sfra_document with documentName: "account"
4. mcp_sfcc-dev_search_sfra_documentation with query: "address"
```
## Enhanced MCP-Guided Controller Template
```javascript
'use strict';
/**
 * [Controller Name] Controller
 * Purpose: [Brief description of controller functionality]
 *
 * Implementation based on Enhanced SFRA Documentation:
 * - mcp_sfcc-dev_get_sfra_categories (discovered 7 categories)
 * - mcp_sfcc-dev_get_sfra_documents_by_category with category: "core"
 * - mcp_sfcc-dev_get_sfra_document with documentName: "server"
 * - mcp_sfcc-dev_get_sfra_document with documentName: "request"
 * - mcp_sfcc-dev_get_sfra_document with documentName: "response"
 * - mcp_sfcc-dev_get_best_practice_guide with guideName: "sfra_controllers"
 * - mcp_sfcc-dev_search_best_practices with query: "security"
 */
var server = require('server');
var Logger = require('dw/system/Logger').getLogger('controllers', 'ControllerName');
// Middleware imports (patterns from enhanced SFRA documentation)
var cache = require('*/cartridge/scripts/middleware/cache');
var csrfProtection = require('*/cartridge/scripts/middleware/csrf');
var userLoggedIn = require('*/cartridge/scripts/middleware/userLoggedIn');
var consentTracking = require('*/cartridge/scripts/middleware/consentTracking');
var pageMetaData = require('*/cartridge/scripts/middleware/pageMetaData');
/**
 * Show endpoint - Display page
 * Patterns from mcp_sfcc-dev_get_sfra_document with documentName: "server"
 * Security from mcp_sfcc-dev_search_best_practices with query: "security"
 */
server.get('Show',
    cache.applyDefaultCache,                    // Caching pattern from SFRA best practices
    consentTracking.consent,                   // Consent tracking from middleware docs
    pageMetaData.computedPageMetaData,         // Page metadata from SFRA patterns
    function (req, res, next) {
        try {
            // Request handling patterns from mcp_sfcc-dev_get_sfra_document "request"
            var queryString = req.querystring;
            var form = req.form;
            var currentCustomer = req.currentCustomer;
            // Input validation (patterns from MCP security guide)
            var validationResult = validateInputs(queryString, form);
            if (!validationResult.valid) {
                Logger.error('Validation failed in ControllerName-Show: {0}', validationResult.error);
                res.setStatusCode(400);
                res.render('error/notfound');
                return next();
            }
            // Business logic using appropriate models
            // Use patterns from category-specific SFRA documents:
            // - Product controllers: mcp_sfcc-dev_get_sfra_document "product-full"
            // - Cart controllers: mcp_sfcc-dev_get_sfra_document "cart"
            // - Customer controllers: mcp_sfcc-dev_get_sfra_document "account"
            var viewData = buildViewData(req);
            // Response patterns from mcp_sfcc-dev_get_sfra_document "response"
            var responseData = sanitizeForTemplate(viewData);
            Logger.info('ControllerName-Show executed successfully');
            res.render('template/templateName', responseData);
        } catch (error) {
            Logger.error('Error in ControllerName-Show: {0}', error.message);
            Logger.debug('Stack trace: {0}', error.stack);
            res.setStatusCode(500);
            res.render('error/servererror');
        }
        next();
    }
);
/**
 * AJAX endpoint example
 * Patterns from enhanced SFRA documentation and security best practices
 */
server.post('UpdateData',
    server.middleware.https,                    // HTTPS enforcement from security patterns
    csrfProtection.validateAjaxRequest,       // CSRF protection from security guide
    userLoggedIn.validateLoggedInAjax,        // Authentication from security patterns
    function (req, res, next) {
        try {
            // AJAX request handling from mcp_sfcc-dev_get_sfra_document "request"
            var requestData = req.form;
            var customer = req.currentCustomer;
            // Validation for AJAX requests
            if (!validateAjaxInput(requestData)) {
                Logger.warn('Invalid AJAX input in ControllerName-UpdateData');
                res.json({
                    success: false,
                    error: 'Invalid input data'
                });
                return next();
            }
            // Process the request using appropriate SFRA models
            var result = processUpdate(requestData, customer);
            // Response patterns from mcp_sfcc-dev_get_sfra_document "response"
            res.json({
                success: true,
                data: sanitizeForJson(result)
            });
            Logger.info('ControllerName-UpdateData completed successfully');
        } catch (error) {
            Logger.error('Error in ControllerName-UpdateData: {0}', error.message);
            res.json({
                success: false,
                error: 'Internal server error'
            });
        }
        next();
    }
);
/**
 * Controller extension example
 * Using patterns from mcp_sfcc-dev_get_best_practice_guide "sfra_controllers"
 */
server.extend(module.superModule);
server.append('Show', function (req, res, next) {
    try {
        // Get existing view data from base controller
        var viewData = res.getViewData();
        // Add custom data using patterns from relevant SFRA model documentation
        viewData.customData = enhanceWithCustomLogic(viewData);
        // Security: Ensure no sensitive data exposure
        viewData = sanitizeCustomData(viewData);
        res.setViewData(viewData);
    } catch (error) {
        Logger.error('Error in ControllerName extension: {0}', error.message);
        // Don't break the chain, let base functionality continue
    }
    next();
});
// Helper functions following SFRA patterns from enhanced documentation
/**
 * Input validation using security patterns from MCP best practices
 */
function validateInputs(queryString, form) {
    // Validation logic based on mcp_sfcc-dev_search_best_practices "security"
    return {
        valid: true, // Implement actual validation
        error: null
    };
}
/**
 * Build view data using appropriate SFRA models
 * Model selection based on controller type and MCP research
 */
function buildViewData(req) {
    // Use patterns from category-specific SFRA documentation:
    // - mcp_sfcc-dev_get_sfra_documents_by_category "product" for product data
    // - mcp_sfcc-dev_get_sfra_documents_by_category "order" for cart/checkout data
    // - mcp_sfcc-dev_get_sfra_documents_by_category "customer" for account data
    var viewData = {};
    // Implement based on controller purpose and SFRA model documentation
    return viewData;
}
/**
 * Sanitize data for template rendering
 * Security patterns from mcp_sfcc-dev_search_best_practices "security"
 */
function sanitizeForTemplate(data) {
    // Implement sanitization based on security best practices
    return data;
}
/**
 * Sanitize data for JSON responses
 * Patterns from SFRA response documentation and security guide
 */
function sanitizeForJson(data) {
    // Remove sensitive fields, format for JSON
    return data;
}
module.exports = server.exports();
```
## š Enhanced Security Patterns
Based on `mcp_sfcc-dev_search_best_practices` with query: "security":
### Input Validation
```javascript
// Use patterns from security best practices guide
function validateInput(input, expectedType, maxLength) {
    // Implement comprehensive validation
}
```
### CSRF Protection
```javascript
// Always use CSRF protection for state-changing operations
server.post('Action', csrfProtection.validateRequest, function(req, res, next) {
    // Implementation
});
```
### Output Sanitization
```javascript
// Sanitize all output to prevent XSS
function sanitizeOutput(data) {
    // Remove script tags, validate HTML, encode special characters
}
```
## š Performance Patterns
From enhanced SFRA documentation and best practices:
### Caching Strategies
```javascript
// Use appropriate cache middleware from SFRA patterns
server.get('Show',
    cache.applyPromotionSensitiveCache,  // For promotion-dependent content
    // or cache.applyDefaultCache,       // For static content
    // or cache.applyInventorySensitiveCache, // For inventory-dependent content
    function(req, res, next) {
        // Controller logic
    }
);
```
### Lazy Loading
```javascript
// Load heavy modules only when needed
server.get('Show', function(req, res, next) {
    var HeavyModel = require('*/cartridge/models/heavyModel'); // Load when needed
    // Use the model
});
```
## š Enhanced Development Checklist
Before deploying any SFRA controller:
- [ ] Used `mcp_sfcc-dev_get_sfra_categories` to understand available documentation
- [ ] Consulted category-specific SFRA documents for relevant models
- [ ] Retrieved `mcp_sfcc-dev_get_best_practice_guide` with "sfra_controllers"
- [ ] Applied security patterns from `mcp_sfcc-dev_search_best_practices` "security"
- [ ] Researched core SFRA classes: server, request, response
- [ ] Used appropriate middleware based on SFRA patterns
- [ ] Implemented proper error handling and logging
- [ ] Applied input validation and output sanitization
- [ ] Used appropriate caching strategies
- [ ] Tested all routes and error conditions
- [ ] Verified CSRF protection for POST endpoints
- [ ] Confirmed proper authentication for protected routes
## šÆ Controller Type-Specific Guidelines
### Product Controllers
Research: `mcp_sfcc-dev_get_sfra_documents_by_category` "product"
Key docs: product-full, product-bundle, product-tile, product-search
### Cart/Checkout Controllers
Research: `mcp_sfcc-dev_get_sfra_documents_by_category` "order"
Key docs: cart, order, billing, shipping, payment, totals
### Customer Controllers
Research: `mcp_sfcc-dev_get_sfra_documents_by_category` "customer"
Key docs: account, address
### Content Controllers
Research: `mcp_sfcc-dev_get_sfra_documents_by_category` "other"
Key docs: categories, content, locale
Remember: Always use the enhanced MCP tools to get current, accurate information about SFRA patterns and best practices!