TypeScript-first library for TOTP and HOTP with multi-runtime and plugin support
otplib is a production-grade JavaScript/TypeScript library for implementing one-time password (OTP) authentication in web and Node.js applications. It provides complete support for both TOTP (Time-Based One-Time Password, RFC 6238) and HOTP (HMAC-Based One-Time Password, RFC 4226), the standards that power Google Authenticator, Authy, and similar 2FA apps.
The library was designed to address the need for a modern, type-safe OTP implementation that works across JavaScript runtimes. With over 1.2 million weekly downloads, it's become the de facto choice for developers building two-factor authentication flows. It handles the cryptographic complexity of HMAC-based token generation while exposing a clean API for secret generation, token creation, and verification.
otplib offers multiple API styles: a high-level Authenticator class for quick Google Authenticator integration, specialized TOTP/HOTP classes for fine-grained control, and a unified OTP class with async support. All implementations follow RFC specifications precisely, including configurable parameters like hash algorithms (SHA1/SHA256/SHA512), token length, time steps, and counter values. The library runs in Node.js, browsers, Deno, and Bun with identical behavior.
Key technical features include Base32 secret encoding, QR code URI generation for easy mobile app pairing, time window tolerance for clock drift, and memory-safe implementations using Uint8Array for secret handling. The TypeScript-first design provides full type safety and IntelliSense support out of the box.
import { authenticator } from 'otplib';
import qrcode from 'qrcode';
class TwoFactorAuth {
async enrollUser(userId: string, email: string): Promise<{ secret: string; qrCode: string }> {
const secret = authenticator.generateSecret();
const otpauthUrl = authenticator.keyuri(email, 'MyApp', secret);
const qrCodeDataUrl = await qrcode.toDataURL(otpauthUrl);
return { secret, qrCode: qrCodeDataUrl };
}
verifyToken(secret: string, token: string): boolean {
return authenticator.verify({ token, secret });
}
verifyWithTolerance(secret: string, token: string): boolean {
return authenticator.verify({
token,
secret,
window: 1
});
}
generateCurrentToken(secret: string): string {
return authenticator.generate(secret);
}
}
const tfa = new TwoFactorAuth();
const { secret, qrCode } = await tfa.enrollUser('user-123', 'user@example.com');
console.log('Secret:', secret);
console.log('QR Code:', qrCode);
const token = tfa.generateCurrentToken(secret);
console.log('Current token:', token);
const isValid = tfa.verifyToken(secret, token);
console.log('Token valid:', isValid);Two-Factor Authentication for Web Apps: Add 2FA to user accounts by generating secrets during enrollment, displaying QR codes for users to scan with Google Authenticator, and verifying tokens at login. otplib handles secret generation, URI formatting, and token validation with configurable time windows to handle clock skew.
API Authentication with TOTP: Secure API endpoints by requiring clients to include time-based tokens alongside API keys. The server generates a shared secret per client, and otplib verifies tokens on each request without database lookups, providing stateless authentication suitable for high-traffic APIs.
Hardware Token Integration: Implement HOTP-based authentication for hardware security tokens that generate counter-based passwords. The library's HOTP class manages counter synchronization and validates tokens even when counters drift due to accidental button presses.
Backup Codes and Recovery: Generate one-time recovery codes for account access when users lose their authenticator devices. Use HOTP with sequential counters to create single-use backup codes that can be safely stored and verified.
Multi-Runtime Authentication Services: Build authentication microservices or edge functions that run across different JavaScript runtimes (Node.js, Cloudflare Workers, Vercel Edge, Deno Deploy). otplib's runtime-agnostic design ensures consistent OTP behavior regardless of deployment environment.
npm install otplibpnpm add otplibbun add otplib