How to Generate Random One-time Password (OTP) in JavaScript

Robin
Updated on December 24, 2022

You can easily generate One-time passwords (OTPs) of any length using JavaScript Math Object. One-time passwords (OTPs) are used to provide an extra layer of security for a website.

We can use them as an additional authentication factor while performing different user actions like user login or changing passwords. You can generate an OPT and send it to the user (e.g. via email or SMS).

OTPs remain valid for a short period of time like 30 seconds or 1 minute to confirm the identity of a user.

In this article, we will cover different methods to generate random OTPs of any length in JavaScript using the Math object.

Normally there are 2 types of one-time passwords (OTPs):

  • Numeric OTPs: The passwords will only contain digits or numbers.
  • Alphanumeric OTPs: The passwords will contain both numbers and alphabets.

We will create both types of OPTs in this article. You can also customize the length of the one-time password according to your requirements.

Generate Numeric(Only Digits) One-time Password in JavaScript

It is very easy to create numeric OTPs using the JavaScript Math object. For that, We will use Math.floor() and Math.random() methods to generate random digits.

Here is the code that you give a random numeric one-time password:

          const generateOTP = (length = 4) => {
    let otp = ''

    for (let i = 0; i < length; i++) {
        otp += Math.floor(Math.random() * 10)
    }

    return otp
}
        

Here I have a generateOTP function that generates a one-time password (OTP) of a specified length. It takes an optional argument called length with a default value of 4. This value will determine the length of the OPT.

I am using a for loop and it will run for the number of iterations specified by the length argument. That means, if the length argument is equal to 4 then the loop will run 4 times.

Inside this for loop, I am generating a random number between 0 and 9 every time the loop runs, and then adding that number to the otp string.

Finally, when the loop completes, the function returns the OTP as a string of numbers.

Here's the output you will get after calling the generateOTP function:

          console.log(generateOTP());  // Outputs a four-digit OTP
// 5170

console.log(generateOTP(6));  // Outputs a six-digit OTP
// 204958
        

When I am not passing any argument to this function, it will generate a 4-digit OTP. But I can generate a 6-digit OTP by passing 6 as its argument. That's how you can get a one-time password of any length.

Also Read: Tricks to Loop Through an Array of Objects in JavaScript

Generate Alphanumeric One-time Password(OTP) in JavaScript

If you want to get more random OTPs, you can combine numbers and alphabets to generate alphanumeric one-time passwords using JavaScript.

Here is the code that you give a random alphanumeric one-time password:

          const generateOTP = (length = 4) => {
    let otp = ''
    const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    for (let i = 0; i < length; i++) {
        const index = Math.floor(Math.random() * characters.length)
        otp += characters[index]
    }

    return otp
}
        

Here I also have a generateOTP function with an optional length argument, which is set to 4 by default.

In this function, I have defined a characters constant, which is a string. It contains all the alphanumeric characters (0-9, A-Z).

Next, I am using a for loop that runs based on the length value. Every time this loop runs, it will generate a random number between 0 and the length of the characters string.

I will use this number as an index to select a character from the characters string, and adds the character to the otp string.

Finally, when the loop completes, the function returns the otp string, which is our OTP.

Here's the output you will get after calling the generateOTP function:

          console.log(generateOTP());  // Outputs a four-digit OTP
// EK6X

console.log(generateOTP(6));  // Outputs a six-digit OTP
// VBEOK3
        

I am calling the generateOTP() function twice to generate 4-digit and 6-digit OTPs. As we can see, our one-time passwords contain both numbers and alphabets.

Also Read: 6 Ways to Check If an Object Has a Property/Key in JavaScript

Conclusion

In this article, We looked at how to generate both numerical and alphanumeric OTPs. While these methods can be useful for certain use cases, it's important to keep in mind that they may not be very secure, as the OTP is based on a random number that can be easily guessed.

It is good practice to generate one-time passwords on the server. If you are using NodeJS for your backend, you can use the crypto module to generate OTPs. It will be much more secure.

But for any reason, if you need it in the browser, you can easily generate random one-time passwords (OTPs) using JavaScript Math object.

Related Posts