lwc-toast-and-notifications
Use when implementing or reviewing user feedback patterns in Lightning Web Components — specifically toast messages, lightning-alert, lightning-confirm, lightning-prompt, and platform notifications. Trigger keywords: 'ShowToastEvent', 'toast in lwc', 'lightning-alert lwc', 'lightning-confirm promise', 'Experience Cloud notification'. NOT for modal overlays (use lwc-modal-and-overlay).
Best use case
lwc-toast-and-notifications is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Use when implementing or reviewing user feedback patterns in Lightning Web Components — specifically toast messages, lightning-alert, lightning-confirm, lightning-prompt, and platform notifications. Trigger keywords: 'ShowToastEvent', 'toast in lwc', 'lightning-alert lwc', 'lightning-confirm promise', 'Experience Cloud notification'. NOT for modal overlays (use lwc-modal-and-overlay).
Teams using lwc-toast-and-notifications should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/lwc-toast-and-notifications/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How lwc-toast-and-notifications Compares
| Feature / Agent | lwc-toast-and-notifications | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Use when implementing or reviewing user feedback patterns in Lightning Web Components — specifically toast messages, lightning-alert, lightning-confirm, lightning-prompt, and platform notifications. Trigger keywords: 'ShowToastEvent', 'toast in lwc', 'lightning-alert lwc', 'lightning-confirm promise', 'Experience Cloud notification'. NOT for modal overlays (use lwc-modal-and-overlay).
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
Use this skill when a component needs to communicate feedback, status, or a decision prompt to the user and the team must choose the right platform primitive. Toast is the default for non-blocking success, warning, and error messages in Lightning Experience; `lightning-alert` and `lightning-confirm` replace browser-native dialogs with promise-based equivalents; platform notifications handle Experience Cloud contexts where toast is invisible.
---
## Before Starting
Gather this context before working on anything in this domain:
- Is the component running in Lightning Experience, Experience Cloud, a mobile app, or an embedded Visualforce page? Toast does not render in Experience Cloud or Visualforce contexts.
- Does the user need to acknowledge the message (blocking) or just be informed (non-blocking)? That choice drives the primitive selection.
- Is the action irreversible? Confirm dialogs are appropriate before destructive operations; toast is not.
---
## Core Concepts
Notification design in LWC centers on matching the interruption level of the primitive to the weight of the event. The platform provides four distinct primitives, and picking the wrong one degrades the experience even when the technical implementation is correct.
### ShowToastEvent and the Toast Contract
`ShowToastEvent` is imported from `lightning/platformShowToastEvent` and fired as a custom event on the component:
```javascript
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
// inside a handler:
this.dispatchEvent(
new ShowToastEvent({
title: 'Record Saved',
message: 'The account was updated successfully.',
variant: 'success',
mode: 'dismissable'
})
);
```
**Parameters:**
| Parameter | Required | Values / Notes |
|---|---|---|
| `title` | Yes | Short heading displayed in bold |
| `message` | No | Body text; supports `{0}`, `{1}` placeholders when `messageData` is provided |
| `variant` | No | `info` (default), `success`, `warning`, `error` |
| `mode` | No | `dismissable` (default), `sticky`, `pester` |
| `messageData` | No | Array of strings or link objects for placeholder substitution in `message` |
**Variants map directly to semantic intent:**
- `info` — neutral informational update
- `success` — completed action (save, approval, send)
- `warning` — non-fatal issue requiring attention
- `error` — operation failed; pair with `sticky` or `pester` so the user cannot miss it
**Modes control dismissal behavior:**
- `dismissable` — the user can click the X to close; auto-closes after a platform-controlled timeout
- `sticky` — persists until the user explicitly closes it; appropriate for errors the user must act on
- `pester` — cannot be closed; disappears on its own after a fixed timeout
**`messageData` for link substitution:**
```javascript
this.dispatchEvent(
new ShowToastEvent({
title: 'Related Record Created',
message: 'A case was opened: {0}. View it {1}.',
messageData: [
'00001234',
{
url: '/lightning/r/Case/500xx000000XXXX/view',
label: 'here'
}
],
variant: 'success'
})
);
```
The `messageData` array must contain exactly as many entries as there are `{n}` placeholders in `message`. A mismatch causes the placeholder text to render literally.
### lightning-alert — Promise-Based Acknowledgment
`lightning-alert` is an inline LWC component that replaces the browser `window.alert()` native dialog. It returns a promise that resolves when the user dismisses it, making control flow explicit:
```javascript
import LightningAlert from 'lightning/alert';
async handleAlertClick() {
await LightningAlert.open({
message: 'You must complete required fields before proceeding.',
theme: 'error',
label: 'Action Required'
});
// execution resumes here after dismissal
}
```
**Parameters:**
| Parameter | Required | Notes |
|---|---|---|
| `message` | Yes | Dialog body text |
| `label` | Yes | Accessible dialog heading (used as `aria-label`) |
| `theme` | No | `default`, `shade`, `inverse`, `alt-inverse`, `success`, `info`, `warning`, `error`, `offline` |
`lightning-alert` is supported in Lightning Experience. It is not supported in Visualforce or standalone HTML pages.
### lightning-confirm — Promise-Based Boolean Decision
`lightning-confirm` prompts the user to confirm or cancel and resolves to `true` (confirmed) or `false` (cancelled):
```javascript
import LightningConfirm from 'lightning/confirm';
async handleDelete() {
const confirmed = await LightningConfirm.open({
message: 'Deleting this record is permanent and cannot be undone.',
theme: 'warning',
label: 'Delete Record'
});
if (confirmed) {
await deleteRecord(this.recordId);
}
}
```
`lightning-confirm` is the correct replacement for the browser `window.confirm()` call inside LWC. It shares the same parameter shape as `lightning-alert`.
### Platform Notifications for Experience Cloud
Toast dispatched from a LWC component is caught and rendered by the Lightning page host. In Experience Cloud (formerly Community Cloud) that host is absent, so toast events bubble up and disappear silently. The correct alternative is the `NotificationsLibrary` wire service from `lightning/platformNotificationService`, which works across Experience Cloud contexts:
```javascript
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
// NOT suitable in Experience Cloud — use below instead
import { ShowNotification } from 'lightning/platformNotificationService';
// available in Experience Cloud builders
```
For components that must work in both contexts, detect the current context via the `@salesforce/client/formFactor` import or use a feature detection pattern, and dispatch the appropriate notification.
---
## Common Patterns
### Toast After Apex DML
**When to use:** A component calls an Apex method to save, update, or delete a record and needs to confirm the outcome to the user without interrupting navigation.
**How it works:** In the `.then()` handler (or in an `async/await` success branch) dispatch a `success` variant toast. In the catch block dispatch an `error` variant toast with `mode: 'sticky'` so the user cannot miss the failure.
**Why not the alternative:** Using `window.alert()` inside LWC is explicitly disallowed by the Locker Service and breaks in Lightning Experience. `lightning-alert` is appropriate for mandatory-read blocking messages, but a simple save confirmation does not need to block the user.
### Confirm Before Destructive Action
**When to use:** The user initiates a delete, archive, or bulk overwrite operation that cannot be reversed.
**How it works:** Open `LightningConfirm` before the Apex call and only proceed if the promise resolves `true`. This pattern makes the gate explicit in code and eliminates the need for manual DOM manipulation or a full `LightningModal` for a single yes/no decision.
**Why not the alternative:** Skipping confirmation for destructive actions is a data integrity risk. Using a full `LightningModal` is heavier than needed for a single-question decision.
---
## Decision Guidance
| Situation | Recommended Approach | Reason |
|---|---|---|
| Confirm save succeeded | `ShowToastEvent` with `variant: 'success'` | Non-blocking; user stays in context |
| Notify user of non-fatal validation issue | `ShowToastEvent` with `variant: 'warning'` | Visible but not blocking |
| Notify user of a recoverable error | `ShowToastEvent` with `variant: 'error', mode: 'sticky'` | Error must persist until the user acts |
| Require acknowledgment before proceeding | `lightning-alert` | Promise resolves after dismissal; explicit control flow |
| Confirm an irreversible destructive action | `lightning-confirm` | Returns boolean; simpler than a full modal |
| Component runs in Experience Cloud | `NotificationsLibrary` / `platformNotificationService` | Toast is invisible outside Lightning page host |
| Complex multi-step confirmation with form fields | `LightningModal` (see `lwc-modal-and-overlay`) | Notification primitives are not form containers |
---
## Recommended Workflow
Step-by-step instructions for an AI agent or practitioner activating this skill:
1. Gather context — confirm the org edition, relevant objects, and current configuration state
2. Review official sources — check the references in this skill's well-architected.md before making changes
3. Implement or advise — apply the patterns from Core Concepts and Common Patterns sections above
4. Validate — run the skill's checker script and verify against the Review Checklist below
5. Document — record any deviations from standard patterns and update the template if needed
---
## Review Checklist
Run through these before marking work in this area complete:
- [ ] The correct variant (`info`, `success`, `warning`, `error`) matches the semantic meaning of the event.
- [ ] `sticky` mode is used only for errors that require user action, not for routine success confirmations.
- [ ] `messageData` placeholder count matches the `{n}` count in `message`.
- [ ] Components deployed to Experience Cloud use `platformNotificationService`, not `ShowToastEvent`.
- [ ] Destructive actions are guarded with `lightning-confirm` before the DML call.
- [ ] Jest tests assert that `ShowToastEvent` was dispatched with the correct parameters.
- [ ] `lightning-alert` and `lightning-confirm` are not used in Visualforce or standalone HTML contexts.
---
## Salesforce-Specific Gotchas
Non-obvious platform behaviors that cause real production problems:
1. **Toast is silent in Experience Cloud** — `ShowToastEvent` bubbles to the Lightning page host. In Experience Cloud that host is absent, so the event fires without rendering. Teams discover this in QA after deploying to a community. Use `platformNotificationService` instead.
2. **`sticky` mode on success toasts is hostile UX** — it requires the user to manually dismiss a non-critical message. Reserve `sticky` for `error` or `warning` variants where the user must acknowledge a problem.
3. **`messageData` placeholder mismatch renders raw template text** — if `message` contains `{0}` but `messageData` is an empty array or contains fewer items, the literal string `{0}` appears to end users. Always validate array length against placeholder count.
4. **`lightning-alert` and `lightning-confirm` are unsupported outside Lightning Experience** — they are not available in Visualforce, standalone pages, or some embedded app contexts. Feature-detect or document the deployment target before choosing these primitives.
---
## Output Artifacts
| Artifact | Description |
|---|---|
| Notification implementation | JavaScript handler using the correct primitive for the scenario |
| Review findings | Issues in variant choice, sticky-mode overuse, and Experience Cloud gaps |
| Jest test pattern | Test verifying toast dispatch with expected parameters |
---
## Related Skills
- `lwc/lwc-modal-and-overlay` — use when the interaction requires a dedicated task container, form input, or a complex result-returning dialog rather than a single-line notification.
- `lwc/lwc-testing` — use alongside this skill when verifying toast dispatch in Jest unit tests.
- `lwc/lifecycle-hooks` — use when notification timing issues are really rerender or async sequencing problems.Related Skills
lwc-show-toast-patterns
ShowToastEvent in LWC: variants (success/warning/error/info), modes (dismissible/pester/sticky), message formatting, NOT supported in LWR Experience Cloud sites, alternatives (lightning-alert, inline banners). NOT for custom notification types (use admin/custom-notification-types). NOT for SLDS popovers.
flow-email-and-notifications
Use when sending emails, in-app bell notifications, SMS, or Slack messages from Salesforce Flow. Trigger keywords: 'send email action', 'custom notification', 'bell icon', 'Send Custom Notification', 'SMS from flow', 'Slack notification flow'. NOT for designing or managing email templates from Setup (use admin/email-templates-and-alerts), and NOT for Email Alerts defined in workflow rules.
xss-and-injection-prevention
Use when writing or reviewing Visualforce pages, Apex controllers, or LWC components that output user-supplied data, build dynamic queries, or construct HTTP responses. Triggers: 'XSS in Visualforce', 'SOQL injection vulnerability', 'how to encode output in Apex', 'JSENCODE Visualforce', 'open redirect prevention'. NOT for Apex CRUD/FLS enforcement (use soql-security or apex-crud-and-fls), NOT for Shield encryption (use shield-encryption-key-management), NOT for AppExchange security review process (use secure-coding-review-checklist).
visualforce-security-and-modernization
Use when hardening or modernizing legacy Visualforce pages — covers the platform CSRF token model and when disabling it is a security regression, view state encryption guarantees and the 170 KB ceiling, FLS/CRUD enforcement gaps on `<apex:outputField>` and on getters that return sObjects, `<apex:includeScript>` interaction with the org Content Security Policy, hosting LWC inside a VF page via `lightning:container` / `lightning-out`, and the retire-vs-harden-vs-leave-alone decision for an inventory of legacy pages. Triggers: 'should I rewrite this Visualforce page in LWC', 'CSRF protection disabled on Visualforce page is that safe', 'community user sees a field they should not on a Visualforce page', 'view state encryption is that enough for sensitive data', 'how do I host an LWC inside a Visualforce page', 'apex:dynamicComponent and apex:actionFunction safe to keep'. NOT for greenfield Visualforce architecture (use apex/visualforce-fundamentals — controller types, view state pattern selection, PDF rendering); NOT for Visualforce email template authoring (use apex/visualforce-email-templates if/when that skill is authored); NOT for general Apex security review across triggers and async (use apex/soql-security and security/secure-coding-review-checklist).
transaction-security-policies
Transaction Security policy creation and configuration: condition builder, enhanced policies, enforcement actions (block, MFA, notification, end session), real-time monitoring mode, and policy troubleshooting. NOT for Event Monitoring log analysis or Shield Event Monitoring setup (use event-monitoring). NOT for Apex testing or debug-log analysis.
sso-saml-troubleshooting
Diagnosing broken SAML SSO into Salesforce — IdP-initiated vs SP-initiated flows, signing-certificate validity / expiry, NameID format mismatches, RelayState handling, audience / entityId / issuer mismatches, clock skew, the SAML Assertion Validator in Setup, the Login History debug log, and the My Domain prerequisite for SSO. Covers the standard diagnostic loop: read the SAML response, identify which check failed, fix at the IdP or SP. NOT for OAuth / OpenID Connect SSO (see security/oauth-openid-troubleshooting), NOT for setting up SSO from scratch (see security/sso-saml-setup).
shield-kms-byok-setup
Configure Shield Platform Encryption with customer-supplied (BYOK) or customer-held (Cache-Only Key Service) tenant secrets, rotate them, and recover. NOT for Classic Encryption or field masking.
shield-event-log-retention-strategy
Use when designing Salesforce Shield Event Monitoring retention, SIEM routing, and storage-tier strategy — which event types to keep, for how long, where, and how to answer audit queries across hot/warm/cold tiers. Triggers: 'shield event log retention', 'route event monitoring to splunk', 'how long to keep login history', 'siem salesforce integration', 'event monitoring storage tier'. NOT for enabling Shield (see salesforce-shield-deployment).
session-management-and-timeout
Use this skill when configuring session timeout values, concurrent session limits, session IP locking, or logout behavior in Salesforce. Covers org-wide session settings, profile-level overrides, Connected App session policies, and Metadata API SecuritySettings deployment. NOT for OAuth token refresh flows, login IP ranges, or MFA/identity-provider configuration.
session-high-assurance-policies
Enforce step-up authentication for sensitive pages/objects using High Assurance session level and login flow policies. NOT for initial MFA enrollment UX.
service-account-credential-rotation
Use when designing credential rotation for integration users, connected apps, named credentials, and OAuth client secrets in Salesforce. Covers rotation cadence, zero-downtime handover, secret storage, and detection of stale credentials. Triggers: 'rotate integration user password', 'connected app secret rotation', 'named credential rotation', 'stale service account', 'zero downtime secret rotation'. NOT for end-user password policies.
security-incident-response
When to use: active or suspected Salesforce org compromise, unauthorized access investigation, attacker containment, forensic evidence collection from EventLogFile/LoginHistory, session revocation, OAuth token cleanup, eradication of attacker persistence, and post-incident recovery verification. Trigger keywords: org compromised, suspicious login, attacker access, session revocation, forensic investigation, breach response, event log forensics, login anomaly investigation, incident response runbook. Does NOT cover general security setup, permission set design, field-level security configuration, or proactive security hardening — those are separate skills. NOT for general security setup.