JAVASCRIPT

Generate Cryptographically Secure Random Tokens

Learn how to generate cryptographically secure random tokens for session IDs, password reset links, and other sensitive operations in your Node.js application using the `crypto` module.

const crypto = require('crypto');

/**
 * Generates a cryptographically secure random token.
 * @param {number} length The length of the token in bytes (e.g., 32 bytes = 64 hex characters).
 * @returns {Promise<string>} A promise that resolves with the hex-encoded token.
 */
async function generateSecureToken(length = 32) {
  return new Promise((resolve, reject) => {
    crypto.randomBytes(length, (err, buffer) => {
      if (err) {
        return reject(err);
      }
      resolve(buffer.toString('hex'));
    });
  });
}

// Example usage:
(async () => {
  try {
    const passwordResetToken = await generateSecureToken(32); // 32 bytes = 64 hex characters
    console.log('Password Reset Token:', passwordResetToken);

    const sessionToken = await generateSecureToken(64); // 64 bytes = 128 hex characters
    console.log('Session Token:', sessionToken);
  } catch (error) {
    console.error('Error generating token:', error);
  }
})();
How it works: Generating truly random tokens is critical for security-sensitive operations like password resets, API keys, or session identifiers. Using predictable or pseudo-random numbers can lead to exploitable vulnerabilities. This Node.js snippet uses the built-in `crypto` module's `randomBytes` function, which generates cryptographically strong pseudo-random data. The `randomBytes` function produces a `Buffer` of the specified length (in bytes), which is then converted to a hexadecimal string for easy use. By defaulting to 32 bytes (64 hex characters), it ensures a sufficiently large and unpredictable token, making brute-force attacks impractical and enhancing the overall security of your application.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs