Skip to main content

Toast Notifications in LWC: ShowToastEvent, Variants & Message Links Guide

In plain words: A Toast Notification in Lightning Web Components (LWC) is a temporary popup banner that delivers instant visual feedback to users when an action completes—such as saving a record, triggering an error, or displaying a system warning. In Salesforce, toasts are dispatched directly from JavaScript using the ShowToastEvent module from lightning/platformShowToastEvent.

Providing clear feedback is essential for building intuitive enterprise user interfaces. Instead of relying on static page text or intrusive browser alert boxes, Salesforce Lightning Experience provides built-in toast banners styled with the Salesforce Lightning Design System (SLDS). By firing custom toast events from your LWC JavaScript files, you can inform users about transaction outcomes, guide them through error resolutions, and link directly to newly created records.

1. Understanding the Toast Notification Architecture in LWC

Toasts in Lightning Web Components work via DOM event bubbling managed by the platform container:

  • The Platform Module: You import ShowToastEvent from the standard library lightning/platformShowToastEvent.
  • The Event Dispatcher: Calling this.dispatchEvent(event) bubbles the event up to the Lightning Experience shell, which renders the animated toast banner at the top of the viewport.
  • Customizable Configuration: You can configure the title, message, visual theme (variant), display behavior (mode), and clickable URL parameters (messageData).
360 LWC Toast Configuration Card:
  • Import Path: import { ShowToastEvent } from 'lightning/platformShowToastEvent';
  • Supported Variants: success (green), error (red), warning (yellow/orange), and info (gray/blue).
  • Supported Modes: dismissable (auto-closes in 3 seconds), pester (stays visible for 3 seconds without a close button), and sticky (stays until user clicks close).
  • Runtime Requirement: Supported in standard Lightning Experience, Salesforce Mobile App, and Lightning Console (requires custom container fallback in LWR/Experience Cloud sites).

2. Step-by-Step Implementation: Toast Variants and Modes

The example below demonstrates how to import the module and trigger success, warning, and error toasts from an LWC controller.

Step 1: Create the HTML Template (toastDemo.html)
<template>
    <lightning-card title="Toast Notification Center" icon-name="custom:custom19">
        <div class="slds-p-around_medium">
            <lightning-button 
                label="Show Success Toast" 
                variant="success" 
                onclick={handleSuccessToast} 
                class="slds-m-right_small">
            </lightning-button>
            
            <lightning-button 
                label="Show Warning Toast" 
                variant="neutral" 
                onclick={handleWarningToast} 
                class="slds-m-right_small">
            </lightning-button>
            
            <lightning-button 
                label="Show Error Toast (Sticky)" 
                variant="destructive" 
                onclick={handleErrorToast}>
            </lightning-button>
        </div>
    </lightning-card>
</template>
Step 2: Implement the JavaScript Controller (toastDemo.js)
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ToastDemo extends LightningElement {

    handleSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Account Created',
            message: 'Enterprise Account has been created successfully.',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    handleWarningToast() {
        const evt = new ShowToastEvent({
            title: 'Incomplete Profile',
            message: 'The billing address is missing for this contact.',
            variant: 'warning',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }

    handleErrorToast() {
        const evt = new ShowToastEvent({
            title: 'System Validation Error',
            message: 'Unable to update opportunity. Review required fields and try again.',
            variant: 'error',
            mode: 'sticky' // Stays on screen until dismissed by user
        });
        this.dispatchEvent(evt);
    }
}

3. Advanced Pattern: Clickable Hyperlinks in Toast Messages

You can embed clickable record links directly inside your toast message by using placeholder tokens ({0}, {1}) combined with the messageData array property.

// Display a success toast containing a direct link to the created record
handleSuccessWithLink(recordId, recordName) {
    const toastEvent = new ShowToastEvent({
        title: 'Success!',
        message: 'Opportunity {0} was created successfully. Click {1} to view.',
        variant: 'success',
        mode: 'sticky',
        messageData: [
            recordName,
            {
                url: `/lightning/r/Opportunity/${recordId}/view`,
                label: 'here'
            }
        ]
    });
    this.dispatchEvent(toastEvent);
}

4. Comparing Toast Display Modes

Mode Behavior Best Use Case
dismissable Visible for 3 seconds or until the user clicks the close button (default). Standard confirmations (e.g., "Record saved").
pester Visible for 3 seconds without a close button. Quick non-critical status updates.
sticky Remains visible indefinitely until the user explicitly clicks the close button. Critical error messages, validation failures, or actionable links.

5. Common Traps & Platform Limitations

Experience Cloud & LWR Trap: Missing Toast Containers
ShowToastEvent relies on the standard Lightning Experience container. In custom Experience Cloud sites (especially Build Your Own LWR sites) or standalone Visualforce containers, standard toasts will fail silently because no parent listener exists to catch the event. For LWR sites, use custom SLDS toast components or third-party modal alert libraries.
Core Rule: Use variant="error" paired with mode="sticky" for system exceptions so users do not miss critical error details, and leverage messageData to provide direct record navigation.
  • Duration Property Limitation: Custom duration parameters are not natively supported by the standard ShowToastEvent API in Lightning Experience; display duration is strictly controlled by the chosen mode.
  • Handle Async Catch Blocks: Always dispatch error toasts inside .catch((error) => { ... }) blocks when calling Apex methods or Lightning Data Service wire adapters to catch backend failures.
  • Sanitize Error Messages: Extract clean error strings using helper utilities (e.g., error.body.message) instead of passing raw exception objects directly into the toast message.

Summary

Toast notifications provide a clean, modern way to keep users informed across transactional workflows in Salesforce Lightning Web Components. By mastering ShowToastEvent, selecting appropriate variants and display modes, and incorporating clickable record links, developers can deliver intuitive, user-friendly enterprise applications.