Skip to main content

Overview

The generateOTP function creates one-time password codes for authentication and verification purposes. It supports both numeric and alphanumeric codes, making it ideal for:
  • Two-factor authentication (2FA)
  • Email verification
  • SMS verification codes
  • Account recovery
  • Transaction confirmation
  • Temporary access codes

Function Signature

import { generateOTP } from 'validauth';

const code = generateOTP(options);

Parameters

options
object
Configuration object for OTP generation
length
number
default:"4"
The number of characters in the OTP code. Common lengths are 4, 6, or 8 digits.
type
string
default:"numeric"
The type of OTP code to generate:
  • "numeric" - Only digits (0-9)
  • "alphanumeric" - Mix of uppercase, lowercase letters and digits (A-Z, a-z, 0-9)
details
boolean
default:"false"
When true, returns an object with detailed information about the generated OTP. When false, returns only the code string.

Return Value

The return type depends on the details parameter:

Basic Mode (details: false)

code
string
The generated OTP code string.

Detailed Mode (details: true)

result
object
Detailed information about the generated OTP
code
string
The generated OTP code string.
length
number
The length of the generated OTP code.
type
string
The type of OTP generated (“numeric” or “alphanumeric”).

Examples

Basic Usage

Generate a 4-digit numeric OTP (default):
import { generateOTP } from 'validauth';

const otp = generateOTP();
console.log(otp); // Example: "7392"

6-Digit OTP

Generate a standard 6-digit verification code:
const code = generateOTP({
  length: 6
});
console.log(code); // Example: "483920"

Alphanumeric OTP

Generate an alphanumeric code for higher security:
const alphaCode = generateOTP({
  length: 8,
  type: 'alphanumeric'
});
console.log(alphaCode); // Example: "aB3xY9mN"

With Detailed Information

Get comprehensive details about the generated OTP:
const result = generateOTP({
  length: 6,
  type: 'numeric',
  details: true
});

console.log(result);
/* Output:
{
  code: "748293",
  length: 6,
  type: "numeric"
}
*/

Short PIN Code

Generate a 4-digit PIN:
const pin = generateOTP({
  length: 4,
  type: 'numeric'
});
console.log(pin); // Example: "8492"

Use Cases

Email Verification

Send a verification code via email:
function sendEmailVerification(email) {
  const verificationCode = generateOTP({
    length: 6,
    type: 'numeric'
  });
  
  // Store code with expiration
  storeVerificationCode(email, verificationCode, '15m');
  
  // Send email
  sendEmail(email, {
    subject: 'Verify your email',
    body: `Your verification code is: ${verificationCode}`
  });
  
  return verificationCode;
}

Two-Factor Authentication

Implement 2FA with OTP codes:
function enable2FA(userId) {
  const code = generateOTP({
    length: 6,
    type: 'numeric',
    details: true
  });
  
  // Store code with short expiration (5 minutes)
  store2FACode(userId, code.code, Date.now() + 5 * 60 * 1000);
  
  return {
    code: code.code,
    expiresIn: '5 minutes'
  };
}

function verify2FA(userId, userCode) {
  const storedCode = get2FACode(userId);
  
  if (!storedCode || Date.now() > storedCode.expiresAt) {
    return { valid: false, error: 'Code expired' };
  }
  
  if (storedCode.code === userCode) {
    delete2FACode(userId);
    return { valid: true };
  }
  
  return { valid: false, error: 'Invalid code' };
}

SMS Verification

Send OTP via SMS:
function sendSMSVerification(phoneNumber) {
  const code = generateOTP({
    length: 6,
    type: 'numeric'
  });
  
  // Store with 10 minute expiration
  storePhoneVerification(phoneNumber, code, '10m');
  
  // Send SMS
  sendSMS(phoneNumber, `Your verification code is ${code}`);
  
  return true;
}

Account Recovery

Generate recovery codes:
function generateRecoveryCodes(userId, count = 10) {
  const codes = [];
  
  for (let i = 0; i < count; i++) {
    const code = generateOTP({
      length: 8,
      type: 'alphanumeric'
    });
    codes.push(code);
  }
  
  // Store recovery codes (hashed)
  storeRecoveryCodes(userId, codes);
  
  return codes;
}

Transaction Confirmation

Require OTP for sensitive operations:
function initiateTransaction(userId, amount) {
  const confirmationCode = generateOTP({
    length: 6,
    type: 'numeric'
  });
  
  // Store transaction pending confirmation
  storePendingTransaction(userId, {
    amount,
    code: confirmationCode,
    expiresAt: Date.now() + 10 * 60 * 1000 // 10 minutes
  });
  
  // Send code to user
  sendTransactionOTP(userId, confirmationCode);
  
  return { pending: true, message: 'Check your phone for confirmation code' };
}

Security Considerations

Important Security Notes:
  • OTP codes should always have an expiration time
  • Limit the number of verification attempts to prevent brute force attacks
  • Use rate limiting to prevent code generation abuse
  • Never log or display OTP codes in production
  • Invalidate codes after successful use
Best Practices:
  • Use 6 digits for standard security
  • Use 8+ characters with alphanumeric for higher security
  • Set expiration times between 5-15 minutes
  • Implement attempt limits (3-5 attempts)
  • Add rate limiting on code generation
  • Use HTTPS for all OTP transmission
  • Consider time-based OTP (TOTP) for higher security needs

Standard Email/SMS Verification

const code = generateOTP({
  length: 6,
  type: 'numeric'
});
// Expiration: 15 minutes
// Attempts: 5

Two-Factor Authentication

const code = generateOTP({
  length: 6,
  type: 'numeric'
});
// Expiration: 5 minutes
// Attempts: 3

High Security Operations

const code = generateOTP({
  length: 8,
  type: 'alphanumeric'
});
// Expiration: 10 minutes
// Attempts: 3

Character Sets

The generator uses the following character sets based on type:
  • Numeric: 0123456789
  • Alphanumeric: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

Integration with Validators

Combine the OTP generator with the OTP validator:
import { generateOTP, validateOTP } from 'validauth';

function createAndStoreOTP(userId) {
  const otp = generateOTP({ length: 6, type: 'numeric' });
  
  // Store with metadata
  storeOTP(userId, {
    code: otp,
    createdAt: Date.now(),
    expiresAt: Date.now() + 15 * 60 * 1000,
    attempts: 0
  });
  
  return otp;
}

function verifyOTP(userId, userCode) {
  const stored = getOTP(userId);
  
  // Validate format first
  const validation = validateOTP(userCode, {
    expectedLength: 6,
    expectedType: 'numeric',
    details: true
  });
  
  if (!validation.valid) {
    return { valid: false, error: 'Invalid OTP format' };
  }
  
  // Check against stored code
  if (stored.code === userCode && Date.now() < stored.expiresAt) {
    deleteOTP(userId);
    return { valid: true };
  }
  
  // Increment attempts
  incrementOTPAttempts(userId);
  return { valid: false, error: 'Invalid or expired OTP' };
}

Build docs developers (and LLMs) love