Node.js Generate Random 6 Digit Number: 3 Ways

How-to basics · Updated November 23, 2026

To generate a random 6-digit number in Node.js, use Math.floor(100000 + Math.random() * 900000). This gives you an integer from 100000 to 999999, inclusive. For a cryptographically secure version (e.g., for OTPs or tokens), use crypto.randomInt(100000, 1000000).

Why You Might Need a 6-Digit Random Number

Six-digit random numbers appear in many real-world applications. Common uses include:

  • One-time passwords (OTPs) sent via SMS or email
  • Two-factor authentication (2FA) codes
  • Email verification codes
  • Order confirmation or tracking numbers
  • Game codes or referral codes

The key difference between these uses is whether you need security or just randomness. A simple random number is fine for a game, but for authentication you need a cryptographically secure generator.

The Basic Method: Math.random()

The simplest approach uses JavaScript’s built-in Math.random(), which returns a floating-point number between 0 (inclusive) and 1 (exclusive). To get a 6-digit integer, you multiply and round:

const randomSixDigit = Math.floor(100000 + Math.random() * 900000);
console.log(randomSixDigit); // e.g., 483920

How it works:

  • Math.random() gives a value like 0.2345
  • Multiply by 900000 gives a range from 0 to 899999.999…
  • Add 100000 shifts the range to 100000 to 999999.999…
  • Math.floor() truncates to the nearest lower integer, ensuring a whole number.

This method is fast and simple, but it is not cryptographically secure. An attacker who can predict Math.random() (which is based on a pseudo-random number generator) could guess your OTP. For security-sensitive uses, use the crypto module instead.

Secure Method: Using crypto.randomInt()

Node.js provides the crypto module, which uses the operating system’s entropy sources to generate truly random numbers. The randomInt() function (available since Node.js 14.10.0) is perfect for this:

const crypto = require('crypto');
const secureSixDigit = crypto.randomInt(100000, 1000000);
console.log(secureSixDigit); // e.g., 592847

Note that randomInt(min, max) returns a number from min (inclusive) to max (exclusive). So to include 999999, you pass 1000000 as the upper bound.

If you need a string (for example, to preserve leading zeros like “001234”), use crypto.randomInt(0, 1000000).toString().padStart(6, '0'). This is common for OTPs where “000123” is valid.

Alternative: Using crypto.randomBytes()

Another secure approach is to generate random bytes and convert them to a number. This is useful if you need a fixed-length string or want to avoid the randomInt API:

const crypto = require('crypto');
const randomBytes = crypto.randomBytes(4).readUInt32BE(0); // 0 to 4294967295
const sixDigit = randomBytes % 900000 + 100000;
console.log(sixDigit);

However, this has a slight modulo bias because 900000 does not divide 2^32 evenly. The bias is tiny (less than 0.0001%) but for high-security applications, randomInt() is preferred because it avoids bias internally.

How to Choose the Right Method

Your choice depends on the use case:

  • Non-security use (e.g., random game number): Use Math.random() – it’s fast and simple.
  • Security-sensitive use (e.g., OTP, password reset): Use crypto.randomInt() – it’s cryptographically secure and unbiased.
  • Need a string with leading zeros: Use crypto.randomInt(0, 1000000).toString().padStart(6, '0').

For most production apps, the secure method is recommended even if you think the number isn’t critical – it costs almost nothing and avoids future vulnerabilities.

Common Pitfalls and Misconceptions

Here are frequent mistakes developers make:

  • Using Math.random() for OTPs – This is a security flaw. Attackers can predict the output if they know the seed.
  • Forgetting to handle leading zeros – A number like “000123” is a valid 6-digit code, but Math.floor() will never produce it. If you need leading zeros, generate a string instead.
  • Using Math.round() instead of Math.floor() – Math.round() can produce 100000 or 1000000, breaking the 6-digit range.
  • Assuming crypto.randomInt is inclusive of the max – It is exclusive, so use 1000000 to get up to 999999.

Another misconception: “6-digit number” sometimes means a number from 000000 to 999999, which includes leading zeros. If that’s your requirement, you need to generate a string, not a number, because JavaScript numbers drop leading zeros.

Performance and Cost Considerations

Performance is rarely an issue for generating a single number. However, if you are generating millions of numbers, Math.random() is faster than crypto.randomInt() because the latter makes a system call. In a high-throughput API, you might use a hybrid: use Math.random() for non-critical IDs and crypto for OTPs.

There is no monetary cost – both methods are built into Node.js. The only “cost” is the slight CPU overhead of the crypto call, which is negligible for typical use.

Frequently Asked Questions

How do I generate a 6-digit number with leading zeros in Node.js?

Use crypto.randomInt(0, 1000000).toString().padStart(6, '0') to get a string like “001234”. If you use Math.random(), you can do Math.floor(Math.random() * 1000000).toString().padStart(6, '0').

Is Math.random() safe for generating OTPs?

No. Math.random() is not cryptographically secure. It is a pseudo-random number generator, and its output can be predicted if the seed is known. Always use crypto.randomInt() for any security-related code.

What is the difference between crypto.randomInt() and crypto.randomBytes()?

Both are secure, but randomInt() is simpler and avoids modulo bias. randomBytes() gives you raw bytes that you must convert, and if you use modulo to get a range, you may introduce bias. Use randomInt() for integer ranges.

Can I generate a random 6-digit number without using the crypto module?

Yes, you can use Math.random() as shown above. It is fine for non-security purposes. For security, you must use the crypto module.

How do I generate multiple unique 6-digit numbers?

Generate a number and store it in a Set to check for duplicates. For example, loop until the Set has the desired count. Be aware that with 900,000 possible numbers, collisions become likely after about 1,000 numbers (birthday paradox).

Does crypto.randomInt() work in browsers?

No, the crypto module is Node.js-specific. In browsers, you can use the Web Crypto API’s crypto.getRandomValues() instead, but the syntax differs.

Final Code Examples

Here’s a complete script that shows both methods side by side:

const crypto = require('crypto');

// Simple method
const simple = Math.floor(100000 + Math.random() * 900000);
console.log('Simple:', simple);

// Secure method
const secure = crypto.randomInt(100000, 1000000);
console.log('Secure:', secure);

// Secure string with leading zeros
const secureString = crypto.randomInt(0, 1000000).toString().padStart(6, '0');
console.log('Secure string:', secureString);

Run this with node script.js to see the output. Remember to use the secure method for anything that protects user data.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.