TOTP API Documentation

Free JavaScript library for generating 2FA codes | ← Back to 2FA.my

Quick Start

Installation

Include the library via CDN or download:

<script src="https://2fa.my/totp-api.js"></script>

Or download and host locally:

<script src="/path/to/totp-api.js"></script>

Basic Usage

// Create a TOTP generator
const totp = new TOTP2FA('JBSWY3DPEHPK3PXP');

// Generate code (async)
const code = await totp.generate();
console.log(code); // "123456"

// Generate code (sync)
const codeSync = totp.generateSync();

// Get remaining seconds
const remaining = totp.getRemaining();
console.log(`Code expires in ${remaining}s`);

🔥 Live Demo

------
Enter a secret and click Generate

Features

🔒 Secure

Uses Web Crypto API when available, constant-time comparison to prevent timing attacks

⚡ Fast

Lightweight (~8KB), no dependencies, sync and async methods available

🔧 Compatible

Works with Google Authenticator, Microsoft Authenticator, Authy, and more

📱 Universal

Works in browsers, Node.js, and any JavaScript environment

API Reference

Constructor

new TOTP2FA(options)
Parameter Type Default Description
secret string required Base32 encoded secret key
digits number 6 Number of digits (4-10)
period number 30 Time period in seconds (10-120)
algorithm string 'SHA1' Hash algorithm (SHA1)
label string '' Account label
issuer string '' Service issuer name

Methods

generate(timestamp?)

Generate TOTP code asynchronously. Returns a Promise.

const code = await totp.generate();
// With custom timestamp
const code = await totp.generate(Date.now() - 30000);

generateSync(timestamp?)

Generate TOTP code synchronously.

const code = totp.generateSync();

verify(code, window?)

Verify a TOTP code. Returns true if valid within the time window.

const isValid = await totp.verify('123456');
// With larger window (±2 periods)
const isValid = await totp.verify('123456', 2);

getRemaining()

Get seconds remaining until current code expires.

const seconds = totp.getRemaining(); // 0-30

getProgress()

Get progress of current period (0-1).

const progress = totp.getProgress(); // 0.0 - 1.0

getURI()

Generate otpauth:// URI for QR codes.

const uri = totp.getURI();
// otpauth://totp/Account?secret=...&digits=6&period=30

Static Methods

TOTP2FA.fromURI(uri)

Create instance from otpauth:// URI.

const totp = TOTP2FA.fromURI('otpauth://totp/GitHub:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=GitHub');

TOTP2FA.generateSecret(length?)

Generate a random Base32 secret.

const secret = TOTP2FA.generateSecret(); // 20 bytes
const secret = TOTP2FA.generateSecret(32); // 32 bytes

Examples

Full Configuration

const totp = new TOTP2FA({
  secret: 'JBSWY3DPEHPK3PXP',
  digits: 6,
  period: 30,
  algorithm: 'SHA1',
  label: '[email protected]',
  issuer: 'MyApp'
});

// Generate and display
setInterval(async () => {
  const code = await totp.generate();
  const remaining = totp.getRemaining();
  console.log(`Code: ${code} (expires in ${remaining}s)`);
}, 1000);

Verify User Input

async function verifyUserCode(userInput) {
  const totp = new TOTP2FA('YOUR_SECRET_HERE');
  
  // Verify with ±1 period window (allows for clock drift)
  const isValid = await totp.verify(userInput, 1);
  
  if (isValid) {
    console.log('✅ Code is valid!');
    return true;
  } else {
    console.log('❌ Invalid code');
    return false;
  }
}

Generate QR Code

const totp = new TOTP2FA({
  secret: TOTP2FA.generateSecret(),
  label: '[email protected]',
  issuer: 'MyApp'
});

const uri = totp.getURI();
// Use any QR library to generate QR code from URI
// Example with qrcode.js:
// QRCode.toCanvas(canvas, uri);
⚠️ Security Warning This is a client-side library. Never expose TOTP secrets in client-side code for production authentication. Use this library for testing, development, or scenarios where the secret is user-provided.

Browser Support

Browser Version Notes
Chrome 60+ Full support with Web Crypto API
Firefox 55+ Full support with Web Crypto API
Safari 11+ Full support with Web Crypto API
Edge 79+ Full support with Web Crypto API
IE 11 11 Software fallback (slower)

License

MIT License - Free for personal and commercial use.

Copyright (c) 2025 2FA.my

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software.