FIELD NOTES • SFRA • STOREFRONT NEXT • REACT • AI
Practical notes from real storefront and AI builds.
“S’know” (stuff I know). Plain-English mental models and code walkthroughs on Salesforce B2C Commerce (SFRA & Storefront Next), modern JavaScript, and practical AI engineering—written from day-to-day project work, no textbook fluff.
The notebook
Latest notes
- The Practical Claude Playbook for Developers: From First Chat to Reusable SystemsMost developers use Claude the same way on day one hundred as they did on day one: open a blank chat, paste a snippet of code or a vague question, get an answer, and start over from scratch tomorrow. That works for quick syntax lookups. It falls apart when you want consistent code reviews, repeatable documentation, or reliable JSON responses inside an application. After digging through Anthropic’s developer patterns and building repeatable workflows of my own, one pattern stood out: getting real leverage from Claude isn’t about finding one magic prompt. It’s about moving up five levels of setup. The five levels Level 1 — Ad-hoc chat Ask a question in one conversation, copy the answer, and lose the working context when you move on. Level 2 — Structured context and artifacts Supply the background, constraints, and examples that matter. Claude Artifacts can help you view and iterate on outputs such as code or documents; they don’t replace project instructions or automatically make context reusable across conversations. Level 3 — Reusable Skills (SKILL.md) Package recurring workflow instructions, domain rules, and output expectations so you don’t have to repeat them each time. Skills improve consistency; they don’t guarantee identical results for every task. Level 4 — Connected tools and MCP Connect Claude to tools or data sources so it can retrieve current information instead of relying on copied snippets. MCP is one way to provide that connection. A tool definition in your own application works differently: Claude requests a function call, and your application runs the function and returns its result. The setup depends on the Claude product; for example, Anthropic’s API MCP connector connects to remote MCP servers. Level 5 — Application pipelines and structured outputs Call Claude from a script or backend route, then constrain the response to a schema when the application needs predictable data. Your code still needs to handle API errors and responses such as refusals or output cut off by a token limit. When an answer feels generic A useful prompt usually makes five things clear: role and bar (who Claude is acting as and what standard it should meet); context (the stack, constraints, and files that matter); task (the exact action); guardrails (what it should avoid); and output contract (the expected response shape). For example, ask for a senior frontend engineer to review a React checkout reducer for race conditions, specify the Storefront Next stack and relevant constraints, ask it to find transitions where a double-click could trigger two basket mutations, rule out third-party state libraries, and request a table of failure modes followed by an updated reducer. Choose the lightest tool that solves the problem One complex task: use a structured prompt and an Artifact to develop a one-time architecture comparison or prototype. Repeated workflow: use a Skill for a process you run regularly, such as reviewing pull requests against team rules. Live data or files: use MCP or another tool connection when Claude needs access to current documentation, repository files, or external data. An application feature: use the Claude API and structured outputs when your code needs a response in a defined format. Keep reusable instructions, reference material, and output schemas separate when that makes them easier to maintain. Putting every rule and edge case into every prompt can bury the details that matter for the current task. What structured outputs add Asking a model to “reply only in valid JSON” is a prompt instruction. Structured outputs let an API request include a JSON Schema, so Claude’s response is constrained to that format. Anthropic documents schema-compliant output as the normal behavior, with exceptions such as refusals and responses cut off at the token limit. Your application still needs to handle those cases. Defining a schema alone doesn’t constrain a response. The application must pass it in the API request, using output_config.format with type: json_schema. The response can then be parsed as JSON, while the application handles API errors, refusals, and incomplete responses. Putting the levels together Here’s one way the five levels can combine while building a feature: 1. Frame the work (Level 2): Turn rough notes into a technical spec and an edge-case checklist. 2. Connect context (Level 4): Let configured tools inspect relevant repository types or schemas. 3. Build in small slices (Levels 2 and 4): Generate one component, loader, or reducer at a time, then check each slice locally. 4. Review consistently (Level 3): Use a Skill with your team’s review criteria, such as checks for timeouts and accessibility. 5. Shape application outputs (Level 5): Use schema-constrained outputs for tasks such as classification or tagging, and handle failure cases in your code. You don’t need a multi-agent system to make the first improvement. Start by making a repeated workflow clearer, then add context, tools, or output constraints when that workflow needs them. Further reading Agent Skills — Claude Platform Docs MCP connector — Claude Platform Docs Structured outputs — Claude Platform DocsRead note
- Stop Writing Wishful AI Prompts: A Developer's Guide to Context & Output ContractsMost developers treat their first AI prompt like a wish tossed into a fountain. You paste a messy React component or CSS snippet, type two quick sentences—“Clean up this product card and make it responsive”—hit Enter, and hope the model guesses your Tailwind conventions, accessibility rules, and prop types. When it removes your aria-label, invents custom CSS classes, or changes your prop names, you spend the next three messages saying, “No, keep the existing props and use our design tokens.” That back-and-forth works for a quick prototype. It breaks when you want consistent UI reviews, reliable component refactors, or predictable JSON payloads in a frontend app. Good prompt writing has nothing to do with secret “magic words.” It comes down to treating a prompt like a typed TypeScript prop contract: clear inputs, explicit boundaries, and a requested return shape. The analogy has limits: a prompt describes expectations, but it doesn’t give the model’s response TypeScript’s compile-time guarantees. Four parts to check before sending For a non-trivial task, define these four parts: 1. Task and standard: State the action and quality bar. For example: “Review this Storefront Next product tile for accessibility gaps and layout shifts.” 2. Scoped context: Give the model only the files, types, or constraints it needs—not automatically your entire repository. 3. Explicit guardrails: Say what it should preserve or avoid. For example: “Do not add external UI libraries. Keep the existing TypeScript prop names.” 4. Output contract: Specify the response shape, such as a Markdown table, unified diff, or JSON object with named keys. A prompt can request a shape; an API schema can enforce one for supported outputs. Use delimiters to separate instructions from input One easy way to weaken a prompt is to mix your instructions and raw input code into one giant wall of prose. Separate tags or Markdown fences make it clearer which text is your instruction and which is the code, stack trace, or user review the model should process. Claude’s prompting guidance recommends XML tags as a way to structure prompts. Tags can help the model distinguish sections, especially in longer prompts; they don’t guarantee instruction-following or make untrusted input safe. Treat code, logs, and user-generated text as data, even when they contain text that looks like an instruction. Show edge cases with examples Describing an edge case in three paragraphs can be harder to follow than showing a couple of input-and-output examples. If you want Claude to classify support tickets or normalize messy catalog attributes into a consistent UI badge format, include realistic <example> pairs in the prompt. Examples can demonstrate tone, formatting, and edge-case choices more directly than a long list of rules. Use examples that represent the cases you care about, and test them; a few examples can guide a response, but they don’t guarantee it will match every case. Treat JSON instructions and JSON enforcement differently If you ask a model for JSON in plain English, it may add “Here is your JSON:” or wrap the object in Markdown fences, which can break JSON.parse(). Use two layers. In an interactive prompt, ask for raw JSON with no fences or commentary, and include an example of the expected shape. This makes your preference clear but remains an instruction. In application code, use API-level structured outputs with a JSON Schema when the provider supports it. This constrains the response format, but your application still needs to handle refusals, truncated output, and whether the returned values make sense for your task. If a prompt takes three follow-up messages to fix formatting or missing constraints, the original prompt may need a clearer output contract. The model can still make mistakes, so use checks that fit the consequences of the task. Keep learning Once you have this prompt structure working, continue with the Practical Claude Playbook for Developers to see how one-off prompts become reusable Skills, MCP connections, and application workflows. Further reading Prompting best practices — Claude Platform Docs Structured outputs — Claude Platform DocsRead note
- SFRA vs. PWA Kit vs. Storefront Next: The Big-Picture Migration Map (2026 Edition)Before we dive into React state machines and route loaders, let’s zoom out and look at the whole map. If you have spent years building on SFRA (Storefront Reference Architecture), hearing terms like Composable Storefront, PWA Kit, Storefront Next, SCAPI, SLAS, and Managed Runtime can make it sound as if the whole tech stack changed overnight. Here is the important starting point: moving to a headless storefront changes how the storefront is built and how it talks to B2C Commerce. The commerce platform still provides capabilities such as products, pricing, baskets, promotions, and orders. The storefront architecture determines where pages are rendered and where application code runs. The Salesforce storefront choices Salesforce documents SFRA, PWA Kit, and Storefront Next as storefront options. Storefront Next is Salesforce’s recommended option for new storefronts. SFRA remains an option for teams that want to use its established server-rendered architecture and B2C Commerce development tools. The right choice depends on your existing implementation and your team’s goals. A useful shorthand: SFRA renders storefront pages in the B2C Commerce application; PWA Kit and Storefront Next run a separate React storefront that communicates with B2C Commerce through APIs. Storefront Next uses React 19, React Router 7, Vite, TypeScript, Tailwind CSS, and shadcn/ui. PWA Kit and Storefront Next: same commerce platform, different patterns PWA Kit and Storefront Next can both use SCAPI and run on Managed Runtime. Their application patterns differ. PWA Kit projects commonly use React components and hooks to request data, with React Query managing server state. Storefront Next uses React Router 7 framework patterns: route loaders retrieve data, and route actions handle mutations. That moves much of a route’s data work out of the component and into the route module. In SFRA, a controller prepares data for an ISML template. In PWA Kit, components may use hooks to retrieve data. In Storefront Next, a route loader can retrieve data before the route renders, and the component uses that loader data. These are useful comparisons, but they are not one-to-one translations. You still need to decide where each responsibility belongs in the new architecture. How a Storefront Next request reaches commerce data Managed Runtime hosts the storefront application. The app can call SCAPI to retrieve or change commerce data, and B2C Commerce still executes the relevant commerce behavior. Managed Runtime also offers a proxy feature for routing API requests through the storefront’s domain. That feature needs configuration; it is not an automatic requirement for every setup. Direct browser requests can use SCAPI’s CORS support when configured for the allowed origins. A migration can happen in stages A team does not have to move every page in one release. A hybrid implementation can route some traffic to a headless storefront and keep other pages on SFRA while the team migrates. Which pages move first depends on the project; product discovery, account, cart, and checkout flows all have their own integration and business requirements. Authentication and shopper state need particular care when shoppers cross between SFRA and a headless storefront. Hybrid Auth synchronizes the session and authorization state; it does not simply exchange one token for another. One possible phased approach 1. Choose a set of routes to serve through the headless storefront. 2. Keep other routes on SFRA while those experiences are being built or validated. 3. Configure routing and authentication for shoppers moving between the two. 4. Move additional routes when their functionality and integrations are ready. The sequence is a project choice, not a universal rule. For example, keeping checkout on SFRA temporarily may be appropriate for one implementation and unsuitable for another. An SFRA-to-Storefront Next translation guide Controller prepares page data → Route loader retrieves data for a route Controller handles a form submission → Route action handles a mutation pdict provides template data → Loader data is consumed by the route component ISML template renders a page → React component renders a route dw.* Script API calls → Sometimes SCAPI, a custom API, or code that remains in B2C Commerce Treat these as starting comparisons, not automatic substitutions. SCAPI does not expose a one-to-one replacement for every Script API or custom business rule. Next, we’ll look at the practical Storefront Next developer experience and how routes connect data loading to rendering: Part 1, Building with Salesforce Storefront Next. Further reading Choose Your B2C Commerce Storefront Type Storefront Next Architecture Migrate from PWA Kit to Storefront Next Hybrid Authentication Overview Use Composable Storefront in a Hybrid Implementation Managed Runtime Proxy Requests CORS in SCAPIRead note
- JavaScript Array Methods: map(), filter(), find(), and reduce() ExplainedYou open a component and see products.filter(...).map(...). Then another file uses find(), and somewhere a reduce() is adding up a basket total. They all take a callback, so it is tempting to think they do roughly the same thing. They do not. Each method asks a different question about an array and returns a different kind of result. Once you know what comes back, the method names become easier to choose—and easier to read in React code. We will use the same small product list throughout. You do not need React to understand the first examples. What data are we working with? products is an array. Each item is an object describing one product. The examples below pass a function—called a callback—to an array method. The method calls that function for the items it processes. What does map() return? Use map() when you want to make a new value for every array item. It returns a new array with the same number of items as the original. For each product, map() calls the callback and puts its returned value in the new array. Here, the callback returns a name, so the result is an array of strings. Think: one input item becomes one output item. If your callback does not return a value, the corresponding output is undefined—a common reason a map() result looks empty or wrong. What does filter() return? Use filter() when you want to keep only the items that pass a test. It returns a new array, which may have fewer items—or none. The callback returns a truthy or falsy result for each item. filter() keeps the items whose test is truthy. Notice the result is still an array, even if only one product matches. Think: which items should stay? What does find() return? Use find() when you want the first item that passes a test. It returns that item itself—not an array. If nothing matches, it returns undefined. Because find() might return undefined, check that a match exists before reading its properties: Think: which first item matches? If you need every match, use filter() instead. What does reduce() return? Use reduce() when you want to combine array items into one accumulated result. That result could be a number, string, object, or another array. For example, we can add the prices of the available products: reduce() calls its callback with an accumulator and the current item. The callback returns the next accumulator value. The final accumulator is the result. Here, total starts at 0 because 0 is the second argument to reduce(). The first available product changes it to 64; the next changes it to 136. Providing an initial value makes the behavior clear and also handles an empty array: reducing an empty array from 0 returns 0. Think: what single result am I building from these items? If a reduce() callback is hard to follow, a plain loop may be clearer. You do not need to use reduce() just because it exists. How do I choose between them? Ask what shape you need next: - Need one output for every item? Use `map()`; you get an array. - Need only the items that pass a test? Use `filter()`; you get an array. - Need the first matching item? Use `find()`; you get an item or undefined. - Need to combine the items into one result? Use `reduce()`; you get the accumulated value. The question is not “Which method looks shortest?” It is “What should the next line receive?” How do these methods show up in React? React commonly uses map() to describe one UI element for each item in a list. The array method is still ordinary JavaScript: it builds an array of results. React then renders those returned elements. Here filter() decides which products to include, and map() makes an <li> description for each one. The key helps React match list items between renders; it does not change what map() returns. One small thing: these methods do not all change the original map(), filter(), and reduce() do not mutate the array they are called on; they return a result. Their callbacks can still mutate objects if you write them to do that. Also, the methods do not automatically make deep copies of objects inside an array. find() returns the original matching item, so changing a property on that returned object changes the object in the original array too. If you are updating data, make sure you understand whether you are creating new objects too. In JavaScript Immutability: Change the Data Without Breaking the Original, we follow that distinction into React state. Want the steps before React? This guide follows JavaScript Before React: A Step-by-Step Guide to the Fundamentals. For object syntax used in the examples, see JavaScript Destructuring and Spread: React and API Examples. When these pieces feel comfortable, continue to React for Salesforce Storefront Next: The Concepts SFRA Developers Need. Further reading Array.prototype.map() — MDN Array.prototype.filter() — MDN Array.prototype.find() — MDN Array.prototype.reduce() — MDNRead note
- Async Programming Without the Footguns: Throughput, Promise.all, and TimeoutsI was looking back at notes from an old backend talk about refactoring a synchronous C# app to asynchronous code. The examples were in C#, but the question stuck with me: if you add async and await, does the app get faster? The answer is more useful than a simple yes or no. Async code does not make one slow API call finish sooner. It can keep your application from waiting unnecessarily, and it lets independent I/O requests overlap. That difference is where throughput improves. Async changes the waiting, not the call’s duration Avoid a request waterfall Suppose a dashboard needs a profile, recent orders, and saved items. If each request is independent, awaiting each one before starting the next creates a waterfall: With those example timings, the loader takes about nine seconds because the waits happen in sequence. If the calls do not depend on each other, start them together and await their results as a group: If those requests take about four, two, and three seconds, the combined wait is roughly four seconds—the slowest request—assuming the services and network can handle the calls concurrently. Keep the sequential version when a later request needs the earlier result. Concurrency is about independent work; it is not a speed boost for each individual request. Give slow requests a timeout Some APIs take too long to respond. Fetch supports an AbortSignal, and modern browsers and Node.js provide AbortSignal.timeout() to create one that aborts after a chosen number of milliseconds: A timeout makes the client stop waiting for the fetch and gives your code a recognizable TimeoutError to handle. For a different kind of cancellation, create an AbortController, pass its signal to fetch, and call abort() when the operation is no longer needed. Neither client-side approach guarantees that a server which already received the request has stopped processing it. For storefront actions that change data, design server-side timeout and retry behavior carefully so a retry cannot accidentally repeat the operation. Refactor one layer at a time When a synchronous helper becomes asynchronous, it returns a Promise. Callers must then handle that Promise: await it, return it, or attach a Promise handler. Starting with a low-level API helper and following the Promise through its callers is one practical way to refactor a codebase. It is a guide, not a rule; the important part is to update each layer’s contract instead of treating a Promise like the final value. Two small reminders from those old notes still help: If you need a result or want the surrounding try/catch to handle a rejection, await the Promise or return it to a caller that handles it. A deliberately fire-and-forget call still needs a rejection handler if it can fail. Keep pure in-memory calculations synchronous unless they truly need asynchronous work. Adding async changes the function to return a Promise; wrapping synchronous work in new Promise() does not make the calculation faster or non-blocking. That is the part of the old talk I keep coming back to: the useful question is not “How do I make await faster?” It is “Which work actually depends on this result, and which work can start now?” Further reading Using promises Promise.all() AbortSignal.timeout() Node.js AbortSignal documentationRead note
- Scope, this, and the Event Loop: How Modern JavaScript Actually RunsBrendan Eich has said JavaScript’s first engine prototype took ten days in May 1995. The language has changed considerably since then, but three execution details still matter in everyday code: scope, `this`, and asynchronous callback scheduling. Why can `this` seem to change when an Add-to-Cart handler runs? And why does a Promise callback sometimes run before a timer? If you work across SFRA controllers and Storefront Next components, these questions lead to three JavaScript rules that are useful to understand: how declarations get their scope, how regular functions receive `this`, and how the event loop schedules asynchronous callbacks. The examples use baskets, promo calculations, click handlers, and SCAPI requests, but the same rules apply to JavaScript in any browser or Node.js application. 1. Scope: why let and const protect basket math A useful mental model is that JavaScript prepares declarations for their scope before running the statements in order. This is a teaching model, not a claim that the engine literally makes exactly two passes over every function. `var` is function-scoped (or script-global at top level), and it is initialized to `undefined` before its assignment runs. `let` and `const` are block-scoped and cannot be accessed before their declaration has initialized them. `vipDiscount` is not available outside the `if` block because `let` is block-scoped. `legacyShippingFee` is available throughout the function because `var` is function-scoped. The second example shows the TDZ: the `promoRate` binding exists in its block, but it has not been initialized yet. In modern code, default to `const`, use `let` when a binding must be reassigned, and generally avoid `var` because its function scope can make values appear outside the block where they were assigned. 2. Finding this: look to the left of the dot For a regular function, `this` depends on how the function is called. “Look to the left of the dot” is a handy shortcut for a direct method call such as `guestCart.logBasketAction()`: When you detach the method, the call is no longer `guestCart.logBasketAction()`, so it does not keep `guestCart` as `this`. In a plain standalone call in strict mode, `this` is `undefined`; trying to read `this.basketId` then throws a TypeError. ES modules are strict mode, which is why this commonly appears in modern JavaScript projects. Callback APIs can supply their own `this`. For example, a browser `addEventListener` callback receives the event’s current target as `this`; it is not the original cart object. Timer callback behavior also depends on the host environment. If a callback needs the cart, pass a wrapper or bind the method explicitly. How arrow functions preserve this in a timer Regular functions receive `this` when they are called. Arrow functions do not create their own `this`; they use the value from the surrounding scope where they were created: 3. The event loop: call stack, microtasks, and tasks JavaScript runs synchronous code to completion on a call stack. In the browser, Promise handlers such as `.then()` run as microtasks. Timers such as `setTimeout()` schedule tasks. After the current synchronous script finishes, the runtime processes queued microtasks before moving on to the next task. This example uses an already-resolved Promise, so its `.then()` callback is queued as a microtask while the script is running. It does not mean a real SCAPI `fetch()` response always beats a timer: the network request may take longer to settle, so its Promise callback might be queued later. A `setTimeout(fn, 1000)` delay is not an exact appointment. The callback becomes eligible after the requested delay, but a busy main thread or browser scheduling can make it run later. If synchronous code is busy parsing a large catalog response, user interactions, timers, and Promise handlers all have to wait for that work to finish. 4. Three rules for today's e-commerce JavaScript Use `const` by default and `let` for reassignment. Block scope and the TDZ help prevent promo or tax variables from leaking across `if` blocks. Use method shorthand for object methods that need the object as `this`; use an arrow callback when you want to preserve the surrounding `this` in a timer or listener. Remember that callback APIs may bind `this` according to their own rules. Keep synchronous work on the call stack short. Fast product-grid filtering helps the browser respond and render; a long-running calculation delays both tasks and microtasks. Interview questions For a prerequisite, read JavaScript Callbacks Explained: How They Work and Why They Matter. To see the Add-to-Cart journey in SFRA, continue with Build Add to Cart: A Backend-to-Frontend SFRA Journey. Further reading Brendan Eich on JavaScript’s first engine prototype JavaScript execution model let and the Temporal Dead Zone The this operator Arrow functions Using promises and task queues Microtask guide HTML Standard: timers As an Amazon Associate I earn from qualifying purchases. JavaScript book used as a source for this article (affiliate link)Read note