How to Generate & Verify One-Time Password (OTP) in LWC

How to Generate & Verify One-Time Password (OTP) in LWC

Introduction: In today’s digital age, security is of utmost importance, especially when dealing with sensitive information. One way to enhance security is by implementing One-Time Password (OTP) verification systems. In this blog post, we’ll explore How to Generate & Verify One-Time Password (OTP) in LWC.

  1. Understanding OTP Generation: OTPs are temporary passwords that are valid for a single login session or transaction. They provide an additional layer of security by requiring users to input a unique code sent to their registered mobile number or email address. Generating OTPs involves creating random alphanumeric strings of a fixed length.
  2. Setting Up Lightning Web Components: Begin by creating a new Lightning Web Component in your Salesforce org. This component will contain the user interface for entering the mobile number and displaying the generated OTP.

LWC Component (OTPGeneratorVerifier):

    <lightning-card title="OTP Generator">
        <div class="slds-m-around_medium">
            <lightning-input label="Enter Mobile Number" type="tel" value={mobileNumber} onchange={handleMobileNumberChange}></lightning-input>
            <lightning-button variant="brand" label="Generate OTP" onclick={generateOTP}></lightning-button>
            <div if:true={otpGenerated}>
                <p>Your OTP is: {otp}</p>
            <div if:true={error}>{error}</div>
import { LightningElement, track } from 'lwc';
import generateOTP from '@salesforce/apex/OTPController.generateOTP';

export default class OTPGeneratorVerifier extends LightningElement {
    @track mobileNumber;
    @track otp;
    @track otpGenerated = false;
    @track error;
    @track email

    handleMobileNumberChange(event) {
        this.mobileNumber =;

    generateOTP() {
        generateOTP({ mobileNumber: this.mobileNumber, email: })
            .then(result => {
                this.otp = result;
                this.otpGenerated = true;
                this.error = undefined;
            .catch(error => {
                this.error = error.body.message;
  1. Writing Apex Controller: Next, create an Apex controller to handle the logic for generating the OTP. Within the controller, define a method that generates a random alphanumeric string of the desired length.

Apex Controller (OTPController):

public with sharing class OTPController {

    public static String generateOTP(String mobileNumber, String email) {
        // Generate OTP
        String otp = generateRandomOTP(6);
        // Send OTP via email
        sendOTPEmail(email, otp);

        // Return the generated OTP
        return otp;

    // Helper method to generate random OTP
    private static String generateRandomOTP(Integer length) {
        String allowedChars = '0123456789';
        String otp = '';
        for(Integer i = 0; i < length; i++) {
            Integer randomIndex = (Integer)Math.floor(Math.random() * allowedChars.length());
            otp += allowedChars.substring(randomIndex, randomIndex + 1);
        return otp;

    // Helper method to send OTP via email
    private static void sendOTPEmail(String email, String otp) {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] { email };
        mail.setSubject('Your OTP for verification');
        mail.setPlainTextBody('Your OTP is: ' + otp);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

This method generates a random OTP of the specified length using characters from the string 0123456789. You can adjust the allowedChars string to include additional characters if you want to generate alphanumeric OTPs.

To use this method, you would call it from your Apex controller or another Apex class:

String otp = OTPGenerator.generateOTP(6); // Generate a 6-digit OTP

Leave a Reply

Your email address will not be published. Required fields are marked *