sf-b2b-lwc
Build Lightning Web Components for Salesforce B2B Commerce storefronts.
Before Writing Code
Fetch live docs BEFORE writing code:
Web-search the latest:
- "Salesforce Lightning Web Components Developer Guide 2026"
- "Salesforce B2B Commerce LWC documentation 2026"
- "lightning/commerce wire adapters 2026"
- "Lightning Web Security LWC 2026"
Web-fetch official sources:
developer.salesforce.com/docs/component-library/documentation/en/lwc
developer.salesforce.com/docs/commerce/salesforce-commerce/guide/lwc-for-b2b.html
developer.salesforce.com/docs/platform/lwc/guide/reference-wire-adapters-intro.html
Verify current decorator syntax, commerce wire adapters, Jest testing patterns, and Lightning Web Security vs Locker behavior.
Conceptual Architecture
Component Structure (4 Parts)
| File |
Purpose |
Notes |
componentName.html |
Template |
{property} binding, lwc:if/lwc:else, for:each |
componentName.js |
Controller |
ES6 class extending LightningElement, decorators, lifecycle hooks |
componentName.css |
Styles |
Component-scoped, :host selector, CSS custom properties |
componentName.js-meta.xml |
Metadata |
API version, targets (Experience Builder, App Builder), exposed properties |
Decorators
| Decorator |
Purpose |
Reactivity |
@api |
Public property (parent-settable) or public method |
Re-renders on change from parent |
@track |
Deep reactivity for objects/arrays |
Only needed for nested mutation (e.g., this.obj.nested = val) |
@wire |
Reactive data fetching from wire adapters |
Re-fetches when reactive ($-prefixed) params change |
Important: Primitive class fields are auto-tracked in modern LWC -- @track is only needed for deep object/array mutation. Reassigning the entire object triggers reactivity without @track.
Lifecycle Hooks
| Hook |
When |
Use For |
constructor() |
Instance created |
Initialize non-reactive state; cannot access DOM or properties |
connectedCallback() |
Inserted into DOM |
Initialization, subscriptions (LMS, platform events) |
renderedCallback() |
After every render |
DOM access; use sparingly (called frequently) |
disconnectedCallback() |
Removed from DOM |
Cleanup listeners, unsubscribe channels, release resources |
errorCallback(error, stack) |
Child component error |
Error boundary; log or display user-friendly messages |
Wire Adapters
Wire adapters provide reactive, cached data fetching. Two binding styles exist:
- Property binding:
@wire(adapter, params) propertyName; -- result is { data, error }
- Function binding:
@wire(adapter, params) functionName({ data, error }) { ... } -- for custom handling
Commerce-specific adapters live under the lightning/commerce and commerce/* namespaces. Fetch live docs for the current list of available commerce wire adapters (products, pricing, cart, inventory).
// Pattern: Wire adapter usage
// Fetch live docs for adapter params
@wire(getProduct, { productId: '$productId' })
product;
Custom Events
Communication from child to parent uses CustomEvent:
| Property |
Purpose |
detail |
Event payload (keep minimal) |
bubbles |
Propagate up the DOM tree |
composed |
Cross shadow DOM boundary |
Parent listens via on[eventname] attribute in template (all lowercase).
Component Communication Patterns
| Direction |
Mechanism |
| Parent to Child |
@api properties set in parent template |
| Child to Parent |
CustomEvent dispatched from child |
| Sibling / Unrelated |
Lightning Message Service (LMS) via publish/subscribe |
Security: Lightning Web Security (LWS)
LWS (default since Spring '23) replaces the legacy Locker Service:
- Native browser security via JavaScript sandboxing
- Shadow DOM enforcement for component isolation
- CSP (Content Security Policy) compliance
- Better performance than legacy Locker
- Supports modern browser APIs
Restrictions: No eval(), no Function(), no setTimeout(string). Use @salesforce/resourceUrl for static resources. Follow CRUD/FLS patterns for data access.
Experience Builder Integration
Components are exposed to Experience Builder via the js-meta.xml file:
- Set
<isExposed>true</isExposed>
- Add
lightningCommunity__Page and lightningCommunity__Default targets
- Define configurable
<property> elements (String, Integer, Boolean, etc.)
- Properties appear in the Experience Builder property panel for drag-and-drop configuration
Jest Testing
LWC components are unit-tested with @salesforce/sfdx-lwc-jest. Key concepts:
- Mock wire adapters and Apex methods with
jest.mock()
- Use
createElement from lwc to instantiate components
- Access rendered DOM via
element.shadowRoot.querySelector()
- Emit mock data from wire adapters; assert DOM changes after
Promise.resolve()
- Clean up DOM in
afterEach to avoid test pollution
// Pattern: Jest test skeleton
// Fetch live docs for mock utilities
import { createElement } from 'lwc';
import MyComponent from 'c/myComponent';
Best Practices
Data Fetching
- Use
@wire for read-only data (reactive, cached via Lightning Data Service)
- Use imperative Apex for mutations (create, update, delete)
- Batch API calls to reduce server round-trips
Performance
- Minimize
renderedCallback logic (runs on every render)
- Use getters for computed values (lazy evaluation)
- Debounce user input handlers
- Lazy-load large components via dynamic imports
Testing
- Write Jest tests for all components
- Mock wire adapters and Apex; test user interactions and error states
- Test accessibility: ARIA attributes, keyboard navigation
B2B Commerce Specific
- Respect buyer context (account, buyer group, entitlements)
- Handle guest vs authenticated experiences
- Display correct per-account pricing and product visibility
- Support multi-currency display in buyer's currency
Fetch the LWC Developer Guide, B2B Commerce LWC docs, and wire adapter reference for exact decorator behavior, adapter parameters, and testing utilities before implementing.
1---2name: sf-b2b-lwc3description: Build B2B Commerce LWC components — Lightning Web Components with @api/@track/@wire decorators, commerce-specific wire adapters, custom events, Lightning Web Security, Jest unit testing, and component lifecycle. Use when building B2B storefront UI components.4allowed-tools: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch5metadata:6 source: https://skillmd.com/skills/orcaqubits/sf-b2b-lwc7---89# sf-b2b-lwc1011Build Lightning Web Components for Salesforce B2B Commerce storefronts.1213## Before Writing Code1415**Fetch live docs BEFORE writing code:**16171. **Web-search** the latest:18 - "Salesforce Lightning Web Components Developer Guide 2026"19 - "Salesforce B2B Commerce LWC documentation 2026"20 - "lightning/commerce wire adapters 2026"21 - "Lightning Web Security LWC 2026"22232. **Web-fetch** official sources:24 - `developer.salesforce.com/docs/component-library/documentation/en/lwc`25 - `developer.salesforce.com/docs/commerce/salesforce-commerce/guide/lwc-for-b2b.html`26 - `developer.salesforce.com/docs/platform/lwc/guide/reference-wire-adapters-intro.html`27283. **Verify** current decorator syntax, commerce wire adapters, Jest testing patterns, and Lightning Web Security vs Locker behavior.2930## Conceptual Architecture3132### Component Structure (4 Parts)3334| File | Purpose | Notes |35|------|---------|-------|36| `componentName.html` | Template | `{property}` binding, `lwc:if`/`lwc:else`, `for:each` |37| `componentName.js` | Controller | ES6 class extending `LightningElement`, decorators, lifecycle hooks |38| `componentName.css` | Styles | Component-scoped, `:host` selector, CSS custom properties |39| `componentName.js-meta.xml` | Metadata | API version, targets (Experience Builder, App Builder), exposed properties |4041### Decorators4243| Decorator | Purpose | Reactivity |44|-----------|---------|-----------|45| `@api` | Public property (parent-settable) or public method | Re-renders on change from parent |46| `@track` | Deep reactivity for objects/arrays | Only needed for nested mutation (e.g., `this.obj.nested = val`) |47| `@wire` | Reactive data fetching from wire adapters | Re-fetches when reactive (`$`-prefixed) params change |4849**Important:** Primitive class fields are auto-tracked in modern LWC -- `@track` is only needed for deep object/array mutation. Reassigning the entire object triggers reactivity without `@track`.5051### Lifecycle Hooks5253| Hook | When | Use For |54|------|------|---------|55| `constructor()` | Instance created | Initialize non-reactive state; cannot access DOM or properties |56| `connectedCallback()` | Inserted into DOM | Initialization, subscriptions (LMS, platform events) |57| `renderedCallback()` | After every render | DOM access; use sparingly (called frequently) |58| `disconnectedCallback()` | Removed from DOM | Cleanup listeners, unsubscribe channels, release resources |59| `errorCallback(error, stack)` | Child component error | Error boundary; log or display user-friendly messages |6061### Wire Adapters6263Wire adapters provide reactive, cached data fetching. Two binding styles exist:6465- **Property binding**: `@wire(adapter, params) propertyName;` -- result is `{ data, error }`66- **Function binding**: `@wire(adapter, params) functionName({ data, error }) { ... }` -- for custom handling6768Commerce-specific adapters live under the `lightning/commerce` and `commerce/*` namespaces. Fetch live docs for the current list of available commerce wire adapters (products, pricing, cart, inventory).6970```javascript71// Pattern: Wire adapter usage72// Fetch live docs for adapter params73@wire(getProduct, { productId: '$productId' })74product;75```7677### Custom Events7879Communication from child to parent uses `CustomEvent`:8081| Property | Purpose |82|----------|---------|83| `detail` | Event payload (keep minimal) |84| `bubbles` | Propagate up the DOM tree |85| `composed` | Cross shadow DOM boundary |8687Parent listens via `on[eventname]` attribute in template (all lowercase).8889### Component Communication Patterns9091| Direction | Mechanism |92|-----------|-----------|93| Parent to Child | `@api` properties set in parent template |94| Child to Parent | `CustomEvent` dispatched from child |95| Sibling / Unrelated | Lightning Message Service (LMS) via `publish`/`subscribe` |9697### Security: Lightning Web Security (LWS)9899LWS (default since Spring '23) replaces the legacy Locker Service:100- Native browser security via JavaScript sandboxing101- Shadow DOM enforcement for component isolation102- CSP (Content Security Policy) compliance103- Better performance than legacy Locker104- Supports modern browser APIs105106**Restrictions:** No `eval()`, no `Function()`, no `setTimeout(string)`. Use `@salesforce/resourceUrl` for static resources. Follow CRUD/FLS patterns for data access.107108### Experience Builder Integration109110Components are exposed to Experience Builder via the `js-meta.xml` file:111- Set `<isExposed>true</isExposed>`112- Add `lightningCommunity__Page` and `lightningCommunity__Default` targets113- Define configurable `<property>` elements (String, Integer, Boolean, etc.)114- Properties appear in the Experience Builder property panel for drag-and-drop configuration115116### Jest Testing117118LWC components are unit-tested with `@salesforce/sfdx-lwc-jest`. Key concepts:119- Mock wire adapters and Apex methods with `jest.mock()`120- Use `createElement` from `lwc` to instantiate components121- Access rendered DOM via `element.shadowRoot.querySelector()`122- Emit mock data from wire adapters; assert DOM changes after `Promise.resolve()`123- Clean up DOM in `afterEach` to avoid test pollution124125```javascript126// Pattern: Jest test skeleton127// Fetch live docs for mock utilities128import { createElement } from 'lwc';129import MyComponent from 'c/myComponent';130```131132## Best Practices133134### Data Fetching135- Use `@wire` for read-only data (reactive, cached via Lightning Data Service)136- Use imperative Apex for mutations (create, update, delete)137- Batch API calls to reduce server round-trips138139### Performance140- Minimize `renderedCallback` logic (runs on every render)141- Use getters for computed values (lazy evaluation)142- Debounce user input handlers143- Lazy-load large components via dynamic imports144145### Testing146- Write Jest tests for all components147- Mock wire adapters and Apex; test user interactions and error states148- Test accessibility: ARIA attributes, keyboard navigation149150### B2B Commerce Specific151- Respect buyer context (account, buyer group, entitlements)152- Handle guest vs authenticated experiences153- Display correct per-account pricing and product visibility154- Support multi-currency display in buyer's currency155156Fetch the LWC Developer Guide, B2B Commerce LWC docs, and wire adapter reference for exact decorator behavior, adapter parameters, and testing utilities before implementing.