Skip to content

otplib API Documentation / @otplib/totp / TOTP

Class: TOTP ​

Defined in: totp/src/class.ts:45

TOTP class for time-based one-time password generation

Example ​

typescript
import { TOTP } from '@otplib/totp';
import { NodeCryptoPlugin } from '@otplib/plugin-crypto-node';
import { ScureBase32Plugin } from '@otplib/plugin-base32-scure';

const totp = new TOTP({
  issuer: 'MyApp',
  label: 'user@example.com',
  crypto: new NodeCryptoPlugin(),
  base32: new ScureBase32Plugin(),
});

const secret = totp.generateSecret();
const token = await totp.generate();
const isValid = await totp.verify(token);

Constructors ​

Constructor ​

new TOTP(options?): TOTP

Defined in: totp/src/class.ts:49

Parameters ​

options? ​

TOTPOptions = {}

Returns ​

TOTP

Methods ​

generate() ​

generate(options?): Promise<string>

Defined in: totp/src/class.ts:76

Generate a TOTP code

Parameters ​

options? ​

Partial<TOTPOptions>

Optional overrides

Returns ​

Promise<string>

The TOTP code

Throws ​

If the algorithm is invalid or unsupported by the plugin

Throws ​

If HMAC computation fails in the crypto plugin


generateSecret() ​

generateSecret(): string

Defined in: totp/src/class.ts:59

Generate a random Base32-encoded secret

Returns ​

string

Base32-encoded secret


toURI() ​

toURI(options?): string

Defined in: totp/src/class.ts:198

Generate an otpauth:// URI for QR codes

When called with parameters, merges them with instance options. This preserves algorithm, digits, and period settings from the instance while allowing label, issuer, and secret to be overridden.

Parameters ​

options? ​

Optional overrides for label, issuer, and secret

issuer? ​

string

label? ​

string

secret? ​

string

Returns ​

string

The otpauth:// URI

Throws ​

If a non-empty algorithm is not supported

Examples ​

Without parameters (uses instance settings)

typescript
const totp = new TOTP({
  label: 'user@example.com',
  issuer: 'MyApp',
  secret: 'JBSWY3DPEHPK3PXP',
  crypto: new NodeCryptoPlugin(),
  base32: new ScureBase32Plugin(),
});
const uri = totp.toURI();

With parameters (overrides instance settings)

typescript
const totp = new TOTP({
  algorithm: 'sha256',
  digits: 8,
  crypto: new NodeCryptoPlugin(),
  base32: new ScureBase32Plugin(),
});
// Uses instance's algorithm and digits with provided label/issuer/secret
const uri = totp.toURI({
  label: 'user@example.com',
  issuer: 'MyApp',
  secret: 'JBSWY3DPEHPK3PXP',
});

verify() ​

verify(token, options?): Promise<VerifyResult>

Defined in: totp/src/class.ts:118

Verify a TOTP code

Parameters ​

token ​

string

The token to verify

options? ​

Partial<Omit<TOTPVerifyOptions, "token">>

Optional verification options

Returns ​

Promise<VerifyResult>

Verification result with validity and optional delta

Throws ​

If the algorithm is invalid or unsupported by the plugin

Throws ​

If HMAC computation fails in the crypto plugin

Released under the MIT License.