Building Dynamic Notifications in LWC
In the ever-evolving landscape of web applications, providing real-time feedback to users is crucial for enhancing the user experience. Notifications play a vital role in informing users about various events, from simple alerts to critical error messages. This article will guide you through the available notification modules and basic code samples which can be used to show dynamic notifications in LWC.
In Salesforce Lightning Web Components (LWC), we have several built-in notification types that help achieve this goal. This article delves into the different types of notifications available in LWC, including LightningAlert.open, LightningConfirm.open, LightningPrompt.open, and ShowToastEvent.
Table of Contents
- Why Do We Need Notifications?
- Types of Notifications in Salesforce LWC
- How to show alerts in LWC
- How to show confirmation dialog in LWC
- How to show prompts in LWC
- How to show ToastMessage in LWC
- Conclusion
Why Do We Need Notifications?
Notifications are an essential part of any interactive web application. They help in:
- Informing Users: Notifications inform users about the status of their actions or system events, ensuring they stay updated.
- Error Handling: Immediate feedback on errors allows users to correct their actions promptly.
- User Engagement: Notifications keep users engaged by providing timely and relevant information.
- Guiding Users: They guide users through processes by confirming actions, prompting for input, or alerting to required tasks.
In Salesforce LWC, notifications are not just about displaying messages; they are about enhancing the overall user experience by providing meaningful and contextual information.
Types of Notifications in Salesforce LWC
- LightningAlert : They are alerts which is used to display alert dialogs to the user.
- LightningConfirm : They are used to provide a confirmation dialog, asking users to confirm or cancel their actions.
- LightningPrompt : They are used to prompt the user for input, such as text or numbers.
- ShowToastEvent : They are used to display toast notifications which disappear after a time.
How to show alerts in LWC
In order to show an alert in LWC we use LightningAlert.open which opens a simple alert dialog to the user. This is useful for providing straightforward information or warnings.
JS Code
import { LightningElement } from 'lwc';
import LightningAlert from 'lightning/alert';
export default class DisplayNotification extends LightningElement {
async handleAlertClick() {
await LightningAlert.open({
message: 'This is the alert message.',
theme: 'error', // 'info', 'success', 'warning', 'error'
label: 'Error!',
}).
// alert modal has been closed
}
}
HTML Code
<template>
<lightning-button onclick={handleAlertClick} label="Open Alert Modal">
</lightning-button>
</template>
Explanation
LightningAlert is used when we want to halt user from performing any action in the application. The alert modal stops the user from performing any action by overlaying a modal on top of the screen.
In order to show alerts in LWC, we need to import LightningAlert from ‘lightning/alert’ in our JS Code.
In the above example we have created a lightning-button which when clicked calls the JS method handleAlertClick and fires LightningAlert.open() from the imported module the display an Alert modal in the UI.
LightningAlert.openmethod is called to display the alert.- The
messageparameter defines the alert content. - The
themeparameter customizes the alert’s appearance. - The
labelparameter sets the title of the alert. - The
.then()method handles actions after the alert is closed.
Demo

Note: We can use LightningAlert.open in place of window.alert() function, which isn’t supported for cross-origin iframe in Chrome and Safari. LightningAlert.open() returns a promise, which means after closing the modal window you can write any code withint the .then() block.

Read the complete salesforce documentation HERE
How to show confirmation dialog in LWC
LightningConfirm.open provides a confirmation dialog, asking users to confirm or cancel their actions. We capture the user response and take different actions in our code.
JS Code
import { LightningElement } from 'lwc';
import LightningConfirm from 'lightning/confirm';
export default class DisplayNotification extends LightningElement {
async handleConfirmClick() {
const result = await LightningConfirm.open({
message: 'This is the confirmation message.',
variant: 'headerless',
label: 'This is the aria-label value',
// label value isn't visible in the headerless variant
});
// confirm modal has been closed
}
}
HTML Code
<template>
<lightning-button onclick={handleConfirmClick} label="Open Confirm Modal">
</lightning-button>
</template>
Explanation
Confirmation Modal is used to ask for user confirmation before proceeding with a certain action.
To use Confirmation Modal we need to import the LightningConfirm from ‘lightning/confirm’ module and just like LightningAlert you need to call LightningConfirm.open().
In our example we have create a lightning-button on click of which a JS method is fired which renders the confirmation modal in the UI.
LightningConfirm.opendisplays the confirmation dialog.- The
messageparameter sets the confirmation message. - The
labelparameter sets the title of the dialog. - The
themeparameter defines the dialog’s appearance. - The
.then()method captures the user’s response (confirm or cancel).
Demo

Note: We can use LightningConfirm.open in place of window.confirm() function, which isn’t supported for cross-origin iframe in Chrome and Safari. LightningConfirm.open() returns a promise, which means after closing the modal window you can write any code withint the .then() block.

Read the complete Salesforce documentation HERE
How to show prompts in LWC
LightningPrompt.open is used to prompt the user for input, such as text or numbers. The user’s prompt inputs can be captured and we can take different actions based on that.
HTML Code
<template>
<lightning-button onclick={handlePromptClick} label="Open Prompt Modal">
</lightning-button>
</template>
JS Code
import { LightningElement } from 'lwc';
import LightningPrompt from 'lightning/prompt';
export default class DisplayNotification extends LightningElement {
handlePromptClick() {
LightningPrompt.open({
message: 'This is the prompt message.',
//theme defaults to "default"
label: 'Please Respond!', // this is the header text
defaultValue: 'Optional initial input value',
}).then((result) => {
// prompt modal has been closed
console.log('Message entered',result);
if(result){
const evt = new ShowToastEvent({
title: 'Prompt User Input',
message: result,
variant: 'success'
});
this.dispatchEvent(evt);
}
});
}
}
Explanation
A prompt modal is used to show a popup which can accept user input.
In order to show popup modal in LWC we need to import LightningPrompt from lightning/prompt module in our JS file, and call LightningPrompt.open() just like the other two modules discussed above.
In our example we created a lightning-button which when clicked will call the JS method handlePromptClick. Inside handlePromptClick we have use the LightningPrompt.open() method from the module to open the prompt modal in our HTML.
LightningPrompt.openmethod is called to display the prompt.- The
messageparameter provides instructions to the user. - The
labelparameter sets the title of the prompt. - The
defaultValueparameter sets a default input value. - The
themeparameter customizes the prompt’s appearance. - The
.then()method captures the user’s input or cancellation.
Demo

Note: We can use LightningAlert.open in place of window.prompt() function, which isn’t supported for cross-origin iframe in Chrome and Safari. LightningPrompt.open() returns a promise, which means after closing the modal window you can write any code withint the .then() block. In our example above we have implemented the callback, after the prompt is closed we show the toast notification.

Read the complete Salesforce documentation HERE
How to show ToastMessage in LWC
ShowToastEvent is used to display toast notifications, which are non-blocking messages that disappear automatically. It doesn’t block the user’s screen.
HTML Code
<template>
<lightning-button onclick={showNotification} label="Show Toast message">
</lightning-button>
</template>
JS Code
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class DisplayNotification extends LightningElement {
showNotification() {
const evt = new ShowToastEvent({
title: 'Title',
message: 'This is a toast message',
variant: 'error'
});
this.dispatchEvent(evt);
}
}
Explanation
A toast message is used to popup a message in the screen that tells the user of a completing action for example: showing a success message after a process initiated by the user is completed or show error if its failed.
In order to use the toast message we need to import ShowToastEvent from the lightning/platformShowToastEvent module in our JS file of the LWC bundle.
Our example uses a lightning-button which calls the JS method (showNotification) to show the toast message in the UI. Inside the showNotification method, we created a new instance of the ShowToastEvent and dispatch it using dispatchEvent. With the below code snippet:
this.dispatchEvent(new ShowToastEvent({
title: 'Validation',
message:'Validation failure',
variant: 'error'
}));
Our article on Working with Apex and Lightning Web Components uses toast message extensively to show the success and error messages while performing different operations.


Read the complete Salesforce documentation HERE
Conclusion
Notifications in Salesforce LWC are powerful tools for enhancing user interaction and providing timely feedback. By leveraging LightningAlert.open, LightningConfirm.open, LightningPrompt.open, and ShowToastEvent, developers can create a variety of dynamic notifications tailored to different scenarios. Understanding how to use these notification types effectively can significantly improve the user experience in your Salesforce applications.
Feel free to use to code snippet given in this article and try these out in your Salesforce instance.
Do let us know your inputs and suggestions in the comment block below.
If you want to stay up to date on the latest LWC use cases, scenarios and hands on project do subscribe to our Newsletter.
For more in-depth tutorials on each notification type, stay tuned for our upcoming blogs where we’ll dive deeper into the specifics of implementing each notification method in LWC.
Related Posts
Boost User Experience: How to Incorporate Icons in lightning datatable
Set background image from static resource in LWC
Understanding the Lifecycle Hooks in LWC
About Author
gouravrocks247
Founder of SFDCRocks247. I love coding and building products which can enhance the user experience, reduce efforts and give better insights into underlying data. www.iamgourav.com