npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

otpkit.js

v1.0.0

Published

Lightweight, secure OTP generation and verification for Node.js applications. Framework-agnostic, production-ready, and easy to integrate.

Downloads

13

Readme

🔐 otpkit.js

Lightweight, secure OTP generation and verification for Node.js applications.

A simple, framework-agnostic library for generating and verifying one-time passwords (OTPs) with bcrypt hashing and built-in expiry management. Perfect for email/SMS verification, password resets, and two-factor authentication flows.


✨ Features

  • 🔒 Secure by Default — OTPs are hashed using bcrypt before storage
  • ⏱️ Built-in Expiry — Automatic TTL (time-to-live) handling
  • 🎯 Zero Configuration — Works out of the box with sensible defaults
  • 📦 Lightweight — Minimal dependencies, small footprint
  • 🔧 Framework Agnostic — Works with Express, Fastify, Koa, Hono, or vanilla Node.js
  • 🎲 Cryptographically Random — Uses Node.js crypto.randomInt() for secure OTP generation
  • 📝 TypeScript Friendly — Clean API with predictable return types

📦 Installation

npm install otpkit.js
yarn add otpkit.js
pnpm add otpkit.js

🚀 Quick Start

import { createOTP, verifyOTP } from "otpkit.js";

// Generate an OTP
const { otp, hash, expiresAt } = await createOTP();

console.log(otp);       // "482916" → Send this to the user (email/SMS)
console.log(hash);      // "$2a$10$..." → Store this in your database
console.log(expiresAt); // 1703001234567 → Unix timestamp when OTP expires

// Later, verify the OTP entered by the user
const result = await verifyOTP({
  otp: "482916",    // User's input
  hash: hash,       // Retrieved from database
  expiresAt: expiresAt
});

if (result.valid) {
  console.log("OTP verified successfully!");
} else {
  console.log("Verification failed:", result.reason);
  // result.reason: "OTP_EXPIRED" | "OTP_INVALID"
}

📖 API Reference

createOTP(options?)

Generates a new OTP with a bcrypt hash.

Parameters

| Parameter | Type | Default | Description | |-----------|----------|---------|--------------------------------------| | length | number | 6 | Length of the OTP (minimum: 4) | | ttl | number | 300 | Time-to-live in seconds (5 minutes) |

Returns

{
  otp: string,        // The plaintext OTP to send to the user
  hash: string,       // Bcrypt hash to store in your database
  expiresAt: number,  // Unix timestamp (ms) when the OTP expires
  ttl: number         // The TTL value used
}

Examples

// Default: 6-digit OTP, 5-minute expiry
const { otp, hash, expiresAt } = await createOTP();

// Custom: 8-digit OTP, 10-minute expiry
const { otp, hash, expiresAt } = await createOTP({ length: 8, ttl: 600 });

// Short-lived: 4-digit OTP, 2-minute expiry
const { otp, hash, expiresAt } = await createOTP({ length: 4, ttl: 120 });

verifyOTP(options)

Verifies an OTP against its hash, checking both validity and expiration.

Parameters

| Parameter | Type | Required | Description | |-------------|----------|----------|----------------------------------------| | otp | string | Yes | The OTP entered by the user | | hash | string | Yes | The bcrypt hash stored in your database| | expiresAt | number | Yes | The expiration timestamp |

Returns

{
  valid: boolean,           // Whether the OTP is valid
  reason: string | null     // null if valid, otherwise "OTP_EXPIRED" or "OTP_INVALID"
}

Examples

// Successful verification
const result = await verifyOTP({ otp: "482916", hash, expiresAt });
// { valid: true, reason: null }

// Expired OTP
const result = await verifyOTP({ otp: "482916", hash, expiresAt: Date.now() - 1000 });
// { valid: false, reason: "OTP_EXPIRED" }

// Invalid OTP
const result = await verifyOTP({ otp: "000000", hash, expiresAt });
// { valid: false, reason: "OTP_INVALID" }

💡 Usage Examples

Email Verification Flow

import { createOTP, verifyOTP } from "otpkit.js";
import { sendEmail } from "./your-email-service.js";
import { db } from "./your-database.js";

// Step 1: User requests email verification
async function requestEmailVerification(userId, email) {
  const { otp, hash, expiresAt } = await createOTP({ ttl: 600 }); // 10 min expiry

  // Store hash and expiry in database
  await db.users.update(userId, {
    emailVerificationHash: hash,
    emailVerificationExpiry: expiresAt
  });

  // Send OTP to user's email
  await sendEmail({
    to: email,
    subject: "Your Verification Code",
    body: `Your verification code is: ${otp}`
  });
}

// Step 2: User submits the OTP
async function verifyEmail(userId, userOtp) {
  const user = await db.users.findById(userId);

  const result = await verifyOTP({
    otp: userOtp,
    hash: user.emailVerificationHash,
    expiresAt: user.emailVerificationExpiry
  });

  if (result.valid) {
    await db.users.update(userId, {
      emailVerified: true,
      emailVerificationHash: null,
      emailVerificationExpiry: null
    });
    return { success: true };
  }

  return { success: false, error: result.reason };
}

Express.js Integration

import express from "express";
import { createOTP, verifyOTP } from "otpkit.js";

const app = express();
app.use(express.json());

// In-memory store (use Redis/DB in production)
const otpStore = new Map();

app.post("/api/otp/send", async (req, res) => {
  const { phone } = req.body;
  const { otp, hash, expiresAt } = await createOTP();

  otpStore.set(phone, { hash, expiresAt });

  // Send OTP via SMS service
  console.log(`Send OTP ${otp} to ${phone}`);

  res.json({ message: "OTP sent successfully" });
});

app.post("/api/otp/verify", async (req, res) => {
  const { phone, otp } = req.body;
  const stored = otpStore.get(phone);

  if (!stored) {
    return res.status(400).json({ error: "No OTP found for this number" });
  }

  const result = await verifyOTP({
    otp,
    hash: stored.hash,
    expiresAt: stored.expiresAt
  });

  if (result.valid) {
    otpStore.delete(phone);
    return res.json({ success: true });
  }

  res.status(400).json({ error: result.reason });
});

app.listen(3000);

🔒 Security Considerations

  1. Never log or expose the plaintext OTP — Only send it to the user via a secure channel
  2. Store only the hash — Never store the plaintext OTP in your database
  3. Implement rate limiting — Prevent brute-force attacks on OTP verification
  4. Use HTTPS — Always transmit OTPs over encrypted connections
  5. Consider attempt limits — Lock out users after multiple failed verification attempts
  6. Clean up expired OTPs — Regularly purge expired OTP records from your database

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


👤 Author

Ashutosh Swamy