1
---
2
name: salesforce-component-standards
3
description: 'Quality standards for Salesforce Lightning Web Components (LWC), Aura components, and Visualforce pages. Covers SLDS 2 compliance, accessibility (WCAG 2.1 AA), data access pattern selection, component communication rules, XSS prevention, CSRF enforcement, FLS/CRUD in AuraEnabled methods, view state management, and Jest test requirements. Use this skill when building or reviewing any Salesforce UI component to enforce platform-specific security and quality standards.'
4
---
5
6
# Salesforce Component Quality Standards
7
8
Apply these checks to every LWC, Aura component, and Visualforce page you write or review.
9
10
## Section 1 — LWC Quality Standards
11
12
### 1.1 Data Access Pattern Selection
13
14
Choose the right data access pattern before writing JavaScript controller code:
15
16
| Use case | Pattern | Why |
17
|---|---|---|
18
| Read a single record reactively (follows navigation) | `@wire(getRecord, { recordId, fields })` | Lightning Data Service — cached, reactive |
19
| Standard CRUD form for a single object | `<lightning-record-form>` or `<lightning-record-edit-form>` | Built-in FLS, CRUD, and accessibility |
20
| Complex server query or filtered list | `@wire(apexMethodName, { param })` on a `cacheable=true` method | Allows caching; wire re-fires on param change |
21
| User-triggered action, DML, or non-cacheable server call | Imperative `apexMethodName(params).then(...).catch(...)` | Required for DML — wired methods cannot be `@AuraEnabled` without `cacheable=true` |
22
| Cross-component communication (no shared parent) | Lightning Message Service (LMS) | Decoupled, works across DOM boundaries |
23
| Multi-object graph relationships | GraphQL `@wire(gql, { query, variables })` | Single round-trip for complex related data |
24
25
### 1.2 Security Rules
26
27
| Rule | Enforcement |
28
|---|---|
29
| No raw user data in `innerHTML` | Use `{expression}` binding in the template — the framework auto-escapes. Never use `this.template.querySelector('.el').innerHTML = userValue` |
30
| Apex `@AuraEnabled` methods enforce CRUD/FLS | Use `WITH USER_MODE` in SOQL or explicit `Schema.sObjectType` checks |
31
| No hardcoded org-specific IDs in component JavaScript | Query or pass as a prop — never embed record IDs in source |
32
| `@api` properties from parent: validate before use | A parent can pass anything — validate type and range before using as a query parameter |
33
34
### 1.3 SLDS 2 and Styling Standards
35
36
- **Never** hardcode colours: `color: #FF3366` → use `color: var(--slds-c-button-brand-color-background)` or a semantic SLDS token.
37
- **Never** override SLDS classes with `!important` — compose with custom CSS properties.
38
- Use `<lightning-*>` base components wherever they exist: `lightning-button`, `lightning-input`, `lightning-datatable`, `lightning-card`, etc.
39
- Base components include built-in SLDS 2, dark mode, and accessibility — avoid reimplementing their behaviour.
40
- If using custom CSS, test in both **light mode** and **dark mode** before declaring done.
41
42
### 1.4 Accessibility Requirements (WCAG 2.1 AA)
43
44
Every LWC component must pass all of these before it is considered done:
45
46
- [ ] All form inputs have `<label>` or `aria-label` — never use placeholder as the only label
47
- [ ] All icon-only buttons have `alternative-text` or `aria-label` describing the action
48
- [ ] All interactive elements are reachable and operable by keyboard (Tab, Enter, Space, Escape)
49
- [ ] Colour is not the only means of conveying status — pair with text, icon, or `aria-*` attributes
50
- [ ] Error messages are associated with their input via `aria-describedby`
51
- [ ] Focus management is correct in modals — focus moves into the modal on open and back on close
52
53
### 1.5 Component Communication Rules
54
55
| Direction | Mechanism |
56
|---|---|
57
| Parent → Child | `@api` property or calling a `@api` method |
58
| Child → Parent | `CustomEvent` — `this.dispatchEvent(new CustomEvent('eventname', { detail: data }))` |
59
| Sibling / unrelated components | Lightning Message Service (LMS) |
60
| Never use | `document.querySelector`, `window.*`, or Pub/Sub libraries |
61
62
For Flow screen components:
63
- Events that need to reach the Flow runtime must set `bubbles: true` and `composed: true`.
64
- Expose `@api value` for two-way binding with the Flow variable.
65
66
### 1.6 JavaScript Performance Rules
67
68
- **No side effects in `connectedCallback`**: it runs on every DOM attach — avoid DML, heavy computation, or rendering state mutations here.
69
- **Guard `renderedCallback`**: always use a boolean guard to prevent infinite render loops.
70
- **Avoid reactive property traps**: setting a reactive property inside `renderedCallback` causes a re-render — use it only when necessary and guarded.
71
- **Do not store large datasets in component state** — paginate or stream large results instead.
72
73
### 1.7 Jest Test Requirements
74
75
Every component that handles user interaction or retrieves Apex data must have a Jest test:
76
77
```javascript
78
// Minimum test coverage expectations
79
it('renders the component with correct title', async () => { ... });
80
it('calls apex method and displays results', async () => { ... }); // Wire mock
81
it('dispatches event when button is clicked', async () => { ... });
82
it('shows error state when apex call fails', async () => { ... }); // Error path
83
```
84
85
Use `@salesforce/sfdx-lwc-jest` mocking utilities:
86
- `wire` adapter mocking: `setImmediate` + `emit({ data, error })`
87
- Apex method mocking: `jest.mock('@salesforce/apex/MyClass.myMethod', ...)`
88
89
---
90
91
## Section 2 — Aura Component Standards
92
93
### 2.1 When to Use Aura vs LWC
94
95
- **New components: always LWC** unless the target context is Aura-only (e.g. extending `force:appPage`, using Aura-specific events in a legacy managed package).
96
- **Migrating Aura to LWC**: prefer LWC, migrate component-by-component; LWC can be embedded inside Aura components.
97
98
### 2.2 Aura Security Rules
99
100
- `@AuraEnabled` controller methods must declare `with sharing` and enforce CRUD/FLS — Aura does **not** enforce them automatically.
101
- Never use `{!v.something}` with unescaped user data in `<div>` unbound helpers — use `<ui:outputText value="{!v.text}" />` or `<c:something>` to escape.
102
- Validate all inputs from component attributes before using them in SOQL / Apex logic.
103
104
### 2.3 Aura Event Design
105
106
- **Component events** for parent-child communication — lowest scope.
107
- **Application events** only when component events cannot reach the target — they broadcast to the entire app and can be a performance and maintenance problem.
108
- For hybrid LWC + Aura stacks: use Lightning Message Service to decouple communication — do not rely on Aura application events reaching LWC components.
109
110
---
111
112
## Section 3 — Visualforce Security Standards
113
114
### 3.1 XSS Prevention
115
116
```xml
117
<!-- ❌ NEVER — renders raw user input as HTML -->
118
<apex:outputText value="{!userInput}" escape="false" />
119
120
<!-- ✅ ALWAYS — auto-escaping on -->
121
<apex:outputText value="{!userInput}" />
122
<!-- Default escape="true" — platform HTML-encodes the output -->
123
```
124
125
Rule: `escape="false"` is never acceptable for user-controlled data. If rich text must be rendered, sanitise server-side with a whitelist before output.
126
127
### 3.2 CSRF Protection
128
129
Use `<apex:form>` for all postback actions — the platform injects a CSRF token automatically into the form. Do **not** use raw `<form method="POST">` HTML elements, which bypass CSRF protection.
130
131
### 3.3 SOQL Injection Prevention in Controllers
132
133
```apex
134
// ❌ NEVER
135
String soql = 'SELECT Id FROM Account WHERE Name = \'' + ApexPages.currentPage().getParameters().get('name') + '\'';
136
List<Account> results = Database.query(soql);
137
138
// ✅ ALWAYS — bind variable
139
String nameParam = ApexPages.currentPage().getParameters().get('name');
140
List<Account> results = [SELECT Id FROM Account WHERE Name = :nameParam];
141
```
142
143
### 3.4 View State Management Checklist
144
145
- [ ] View state is under 135 KB (check in browser developer tools or the Salesforce View State tab)
146
- [ ] Fields used only for server-side calculations are declared `transient`
147
- [ ] Large collections are not persisted across postbacks unnecessarily
148
- [ ] `readonly="true"` is set on `<apex:page>` for read-only pages to skip view-state serialisation
149
150
### 3.5 FLS / CRUD in Visualforce Controllers
151
152
```apex
153
// Before reading a field
154
if (!Schema.sObjectType.Account.fields.Revenue__c.isAccessible()) {
155
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'You do not have access to this field.'));
156
return null;
157
}
158
159
// Before performing DML
160
if (!Schema.sObjectType.Account.isDeletable()) {
161
throw new System.NoAccessException();
162
}
163
```
164
165
Standard controllers enforce FLS for bound fields automatically. **Custom controllers do not** — FLS must be enforced manually.
166
167
---
168
169
## Quick Reference — Component Anti-Patterns Summary
170
171
| Anti-pattern | Technology | Risk | Fix |
172
|---|---|---|---|
173
| `innerHTML` with user data | LWC | XSS | Use template bindings `{expression}` |
174
| Hardcoded hex colours | LWC/Aura | Dark-mode / SLDS 2 break | Use SLDS CSS custom properties |
175
| Missing `aria-label` on icon buttons | LWC/Aura/VF | Accessibility failure | Add `alternative-text` or `aria-label` |
176
| No guard in `renderedCallback` | LWC | Infinite rerender loop | Add `hasRendered` boolean guard |
177
| Application event for parent-child | Aura | Unnecessary broadcast scope | Use component event instead |
178
| `escape="false"` on user data | Visualforce | XSS | Remove — use default escaping |
179
| Raw `<form>` postback | Visualforce | CSRF vulnerability | Use `<apex:form>` |
180
| No `with sharing` on custom controller | VF / Apex | Data exposure | Add `with sharing` declaration |
181
| FLS not checked in custom controller | VF / Apex | Privilege escalation | Add `Schema.sObjectType` checks |
182
| SOQL concatenated with URL param | VF / Apex | SOQL injection | Use bind variables |
183