Database-less OTP Verification

1.0.6 · active · verified Wed Apr 22

otp-without-db is a Node.js library, currently at version 1.0.6, designed for secure, database-less One-Time Password (OTP) verification. It leverages Node.js's built-in `crypto` module to create and verify HMAC-based hashes that encapsulate the OTP, recipient identifier (phone/email), and an expiration timestamp. This approach eliminates the need for persistent storage of OTPs on the server side, reducing database load and potential attack surface. The library's core functionality revolves around `createNewOTP` for generating a verifiable hash and `verifyOTP` for validating user-submitted credentials against that hash. While it handles verification, users must implement their own OTP generation (e.g., using `otp-generator`) and delivery mechanisms (SMS, email). The project has a relatively slow release cadence, suggesting a stable, feature-complete state since its initial publication. Its primary differentiator is the stateless, cryptographic verification model, which relies heavily on a shared secret key for security.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the full workflow of generating an OTP hash, simulating user input, and verifying the OTP without a database, using `otp-generator` and `otp-without-db`.

import { createNewOTP, verifyOTP } from 'otp-without-db';
import otpGenerator from 'otp-generator';

// Ensure you have otp-generator installed: npm install otp-generator

const SECRET_KEY = process.env.OTP_SECRET_KEY ?? 'your-very-secret-key-that-you-must-change-in-production-!!!!';
const userIdentifier = "+15551234567"; // Can be phone number or email
const expiresInMinutes = 5;

// 1. Generate OTP (using an external library like otp-generator)
const otp = otpGenerator.generate(6, { upperCaseAlphabets: false, specialChars: false, lowerCaseAlphabets: false });
console.log(`Generated OTP: ${otp}`);

// 2. Create a secure hash to send to the user (and keep track of on your server, if needed for context)
// This hash implicitly contains the identifier, OTP, and expiration time.
const hash = createNewOTP(userIdentifier, otp, SECRET_KEY, expiresInMinutes);
console.log(`Generated Hash: ${hash}`);

// In a real application, you would now send 'otp' to the user via SMS/email and 'hash' back to the client.
// For demonstration, we simulate the user receiving and sending back the details.

// --- User verification step (e.g., in an API endpoint) ---
const userProvidedOTP = otp; // User enters this, received via SMS/email
const userProvidedHash = hash; // Client sends this back, received in step 2
const userProvidedIdentifier = userIdentifier; // Client sends this back

// 3. Verify the OTP hash
const isVerified = verifyOTP(userProvidedIdentifier, userProvidedOTP, userProvidedHash, SECRET_KEY);

if (isVerified) {
  console.log("OTP Verified Successfully!");
} else {
  console.log("OTP Verification Failed or Expired.");
}

view raw JSON →