DEV Community

Kai
Kai

Posted on • Edited on • Originally published at kais.blog

8

How to Generate a Secure Random Number in Node.js

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.

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video 🎥

Top comments (4)

Collapse
 
michalorman profile image
Michał Orman

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

Collapse
 
kais_blog profile image
Kai

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

Collapse
 
huncyrus profile image
huncyrus

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

Collapse
 
phroca profile image
philippe roca

Or you can use random-number-csprng for generation number in a range.

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay