DEV Community

loading...

How to Generate a Secure Random Number in Node.js

Kai
Hey 👋 I'm a 👨‍💻 Business IT Specialist / Full Stack Dev | ❤ Follow me to Move Your Learning Forward together!
Originally published at kais.blog Updated on ・2 min read

This post was originally published at kais.blog.

Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!


While you are working on your JavaScript apps, the moment will come when you need a secure random number. Generating it has been quite tricky in the past. Some people use Math.random whenever the need for a random number arises. Please don't do this if there is any chance for an attacker.

If you are generating random numbers for security reasons (e.g. verification codes), you should use a cryptographically secure random number. Fortunately, the crypto module has been extended in recent Node.js versions. So, now there's an easy way to do it in JavaScript.

Prerequisites

  • Node.js (v14.10.0+ / v12.19.0+)

Generate a Secure Random Number Between min and max in JavaScript

Without further ado, let's generate our secure random number. First, import the crypto module:

const crypto = require("crypto");
Enter fullscreen mode Exit fullscreen mode

Now, you have access to the randomInt function. randomInt takes up to three arguments.

Probably, you want to generate a random number in a given range. Therefore, you can specify the minimum (min) and maximum (max). Note that the minimum is inclusive and the maximum is exclusive. So, if you want to generate a number between 0 and 999,999 you'll have to pass 0 and 1000000.

// Synchronous
const n = crypto.randomInt(0, 1000000);
console.log(n);
Enter fullscreen mode Exit fullscreen mode

The third argument is optional. You can provide a callback function. Then, the random integer is generated asynchronously:

// Asynchronous
crypto.randomInt(0, 1000000, (err, n) => {
  if (err) throw err;
  console.log(n);
});
Enter fullscreen mode Exit fullscreen mode

Good! Now, n is a secure random integer between 0 and 999999. For example, this could be used as a 6-digit verification code:

const verificationCode = n.toString().padStart(6, "0");
Enter fullscreen mode Exit fullscreen mode

Conclusion

The changes in recent Node.js versions made generating secure random numbers easy. So, if you are generating random numbers to use as verification codes or for a secure random shuffle, you now know how to do it.


Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!

This post was originally published at kais.blog.

Discussion (3)

Collapse
michalorman profile image
Michał Orman

I believe it should be padStart(6, "0")

Collapse
kais_blog profile image
Kai Author

Yep, you are right! I fixed the post. Thank you!

Collapse
huncyrus profile image
huncyrus

Nice. Alternatively can be used UUID (v4) as well.