Overview
The generatePassword function creates cryptographically random passwords based on your specified requirements. It’s perfect for:
- User registration flows requiring auto-generated passwords
- Password reset functionality
- API key generation
- Temporary credential creation
- Security testing and development
Function Signature
import { generatePassword } from 'validauth';
const password = generatePassword(options);
Parameters
Configuration object for password generationThe desired length of the password. Longer passwords are more secure.
Whether to include uppercase letters (A-Z) in the password.
Whether to include lowercase letters (a-z) in the password.
Whether to include numeric digits (0-9) in the password.
Whether to include special symbols (!@#$%^&*()-_=+[]|;:,.) in the password.
When true, returns an object with detailed information including password strength analysis. When false, returns only the password string.
Return Value
The return type depends on the details parameter:
Basic Mode (details: false)
The generated password string.
Detailed Mode (details: true)
Detailed information about the generated passwordThe generated password string.
The actual length of the generated password.
Array of error messages if any validation failed (e.g., no character types selected).
Password strength analysis object returned from the password validator. Includes strength score, recommendations, and security metrics.
Examples
Basic Usage
Generate a password with default settings (12 characters, all character types):
import { generatePassword } from 'validauth';
const password = generatePassword();
console.log(password); // Example: "aB3$xY9&mN2!"
Custom Length
Generate a longer, more secure password:
const strongPassword = generatePassword({
length: 24
});
console.log(strongPassword); // Example: "xK8#mP2$vN9!qR4&sT7@wY5%"
Alphanumeric Only
Generate a password without special symbols:
const alphanumeric = generatePassword({
length: 16,
includeSymbols: false
});
console.log(alphanumeric); // Example: "aB3xY9mN2kP7qR4s"
Numeric PIN
Generate a numeric-only password:
const pin = generatePassword({
length: 6,
includeUppercase: false,
includeLowercase: false,
includeSymbols: false
});
console.log(pin); // Example: "483920"
Get comprehensive details about the generated password:
const result = generatePassword({
length: 16,
details: true
});
console.log(result);
/* Example output:
{
password: "xK8#mP2$vN9!qR4&",
length: 16,
errors: [],
strength: {
score: 4,
verdict: "strong",
recommendations: [],
// ... additional strength metrics
}
}
*/
Error Handling
Handle cases where no character types are selected:
const result = generatePassword({
includeUppercase: false,
includeLowercase: false,
includeNumbers: false,
includeSymbols: false,
details: true
});
console.log(result);
/* Output:
{
password: "",
errors: ["At least one character type must be selected."]
}
*/
Use Cases
User Registration
Generate a temporary password for new users:
function createUserAccount(email) {
const tempPassword = generatePassword({
length: 12,
includeSymbols: true
});
// Send welcome email with temp password
sendWelcomeEmail(email, tempPassword);
return tempPassword;
}
Password Reset
Generate a secure reset password:
function resetUserPassword(userId) {
const newPassword = generatePassword({
length: 16,
details: true
});
if (newPassword.strength.score >= 3) {
updateUserPassword(userId, newPassword.password);
return newPassword.password;
}
// Regenerate if not strong enough
return resetUserPassword(userId);
}
API Key Generation
Create API keys using alphanumeric characters:
function generateApiKey() {
return generatePassword({
length: 32,
includeSymbols: false,
includeUppercase: true,
includeLowercase: true,
includeNumbers: true
});
}
Security Considerations
The generated passwords use Math.random() which is suitable for most applications but not for cryptographic purposes requiring high security. For production systems handling sensitive data, consider using a cryptographically secure random number generator.
Best Practices:
- Use at least 12 characters for general passwords
- Use 16+ characters for high-security applications
- Include all character types for maximum entropy
- Always validate generated passwords with the password validator
- Store passwords securely using proper hashing (bcrypt, Argon2)
Integration with Validators
Combine the password generator with the password validator for complete password management:
import { generatePassword } from 'validauth';
import { validatePassword } from 'validauth';
function createSecurePassword() {
let password;
let isValid = false;
while (!isValid) {
password = generatePassword({ length: 16 });
const validation = validatePassword(password, { details: true });
if (validation.valid && validation.strength.score >= 4) {
isValid = true;
}
}
return password;
}
Character Sets
The generator uses the following character sets:
- Uppercase:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
- Lowercase:
abcdefghijklmnopqrstuvwxyz
- Numbers:
0123456789
- Symbols:
!@#$%^&*()-_=+[]{}|;:,.<>?