JAVASCRIPT
Generate Cryptographically Secure Random Tokens in Node.js
Learn to generate strong, unpredictable random tokens in Node.js using the built-in `crypto` module for secure password resets, API keys, and session IDs.
const crypto = require('crypto');
/**
* Generates a cryptographically secure random token.
* @param {number} length The desired length of the token in bytes (defaults to 32).
* @returns {Promise<string>} A promise that resolves to the hex-encoded token string.
*/
async function generateSecureToken(length = 32) {
return new Promise((resolve, reject) => {
crypto.randomBytes(length, (err, buffer) => {
if (err) {
return reject(err);
}
resolve(buffer.toString('hex'));
});
});
}
// Usage examples:
(async () => {
try {
const sessionToken = await generateSecureToken(64); // 128 hex characters
console.log('Session Token:', sessionToken);
const passwordResetToken = await generateSecureToken(20); // 40 hex characters
console.log('Password Reset Token:', passwordResetToken);
const shortVerificationCode = await generateSecureToken(3); // 6 hex characters
console.log('Short Verification Code:', shortVerificationCode);
// Using synchronous version for simpler cases, but async is generally preferred
const syncToken = crypto.randomBytes(16).toString('hex');
console.log('Synchronous Token (16 bytes):', syncToken);
} catch (error) {
console.error('Error generating token:', error);
}
})();
How it works: This Node.js snippet demonstrates how to generate cryptographically secure random tokens using the `crypto` module. Unlike `Math.random()`, `crypto.randomBytes()` generates random data that is suitable for security-sensitive applications like session IDs, API keys, and password reset tokens. The function `generateSecureToken` wraps `randomBytes` in a Promise, converting the raw buffer to a more usable hexadecimal string. This ensures the generated tokens are unpredictable and robust against brute-force attacks.