@verifykit.io/2fa
v1.0.0
Published
Official Node.js SDK for VerifyKit 2FA - Two-factor authentication via Email OTP
Maintainers
Readme
VerifyKit 2FA Node.js SDK
Official Node.js SDK for VerifyKit 2FA - Two-factor authentication via Email OTP.
Features
- Simple & Intuitive - Send and verify OTP codes in two API calls
- Fast & Reliable - Built-in retry logic with exponential backoff
- TypeScript First - Full TypeScript support with complete type definitions
- Automatic Retries - Smart retry logic for network and server errors
- Rate Limit Handling - Automatic rate limit detection and retry
- ESM & CommonJS - Supports both module systems
- Custom Errors - Detailed error classes for better error handling
- Secure - SHA-256 hashed codes, auto-expiry, max 5 attempts
Installation
# npm
npm install @verifykit.io/2fa
# yarn
yarn add @verifykit.io/2fa
# pnpm
pnpm add @verifykit.io/2faQuick Start
import { VerifyKit2FA } from '@verifykit.io/2fa';
const client = new VerifyKit2FA({
apiKey: process.env.VERIFYKIT_API_KEY! // Get your API key from https://verifykit.io/dashboard/api-keys
});
// Send an OTP code
const { request_id } = await client.sendOtp('[email protected]');
// Verify the code entered by the user
const result = await client.verifyOtp(request_id, '123456');
console.log(result.valid); // true or falseTable of Contents
- Installation
- Quick Start
- Authentication
- Usage Examples
- Configuration
- API Reference
- Error Handling
- TypeScript Support
- Advanced Features
- Contributing
- License
Authentication
Get your API key from the VerifyKit Dashboard. 2FA requires a Growth, Pro, or Unlimited plan.
import { VerifyKit2FA } from '@verifykit.io/2fa';
const client = new VerifyKit2FA({
apiKey: process.env.VERIFYKIT_API_KEY!
});Environment Variables:
# .env file
VERIFYKIT_API_KEY=vk_live_your_api_key_hereUsage Examples
Send OTP Code
import { VerifyKit2FA } from '@verifykit.io/2fa';
const client = new VerifyKit2FA({
apiKey: process.env.VERIFYKIT_API_KEY!
});
const result = await client.sendOtp('[email protected]');
console.log({
request_id: result.request_id, // Save this to verify later
expires_in: result.expires_in, // Seconds until code expires (default: 600)
message: result.message // Status message
});Verify OTP Code
// After the user enters their code
const verification = await client.verifyOtp(request_id, '847293');
if (verification.valid) {
console.log('User verified!');
} else {
console.log('Invalid code:', verification.message);
}Custom App Name
Brand the verification email with your app name:
const result = await client.sendOtp('[email protected]', {
appName: 'MyApp' // Displayed in the verification email (max 50 chars)
});API Delivery Mode
Get the OTP code in the API response instead of sending via email, so you can deliver it yourself:
const result = await client.sendOtp('[email protected]', {
delivery: 'api' // Returns the code in the response
});
console.log(result.code); // '847293' - deliver this yourself via SMS, push, etc.Configuration
const client = new VerifyKit2FA({
// Required: Your API key (use environment variable)
apiKey: process.env.VERIFYKIT_API_KEY!,
// Optional: Base URL (default: 'https://api.verifykit.io')
baseUrl: 'https://api.verifykit.io',
// Optional: Request timeout in milliseconds (default: 30000)
timeout: 30000,
// Optional: Maximum number of retries (default: 3)
maxRetries: 3,
// Optional: Enable debug logging (default: false)
debug: true,
// Optional: Custom headers
headers: {
'X-Custom-Header': 'value'
}
});API Reference
sendOtp(email, options?)
Send a 2FA OTP verification code to an email address.
Parameters:
email(string): The email address to send the code tooptions(object, optional):appName(string): Your app name for the verification email (max 50 chars)delivery('email'|'api'): Delivery mode (default:'email')
Returns: Promise<SendOtpResult>
Example:
const result = await client.sendOtp('[email protected]', {
appName: 'MyApp',
delivery: 'email'
});verifyOtp(requestId, code)
Verify a 2FA OTP code.
Parameters:
requestId(string): Therequest_idfromsendOtpcode(string): The 6-digit code entered by the user
Returns: Promise<VerifyOtpResult>
Example:
const result = await client.verifyOtp('2fa_abc123...', '847293');
console.log(result.valid); // true or falseError Handling
The SDK provides detailed error classes for different scenarios:
import {
VerifyKit2FA,
ValidationError,
AuthenticationError,
ForbiddenError,
RateLimitError,
TimeoutError,
NetworkError,
ServerError,
VerifyKit2FAError
} from '@verifykit.io/2fa';
try {
await client.sendOtp('[email protected]');
} catch (error) {
if (error instanceof ValidationError) {
console.log('Invalid input:', error.message);
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key:', error.message);
} else if (error instanceof ForbiddenError) {
console.log('2FA not available on your plan:', error.message);
} else if (error instanceof RateLimitError) {
console.log('Rate limit exceeded, retry after:', error.retryAfter);
} else if (error instanceof TimeoutError) {
console.log('Request timeout:', error.timeout);
} else if (error instanceof NetworkError) {
console.log('Network error:', error.message);
} else if (error instanceof ServerError) {
console.log('Server error:', error.message);
} else if (error instanceof VerifyKit2FAError) {
console.log('VerifyKit error:', error.message);
} else {
console.error('Unknown error:', error);
}
}Error Properties
All VerifyKit 2FA errors include:
name: Error class namemessage: Human-readable error messagecode: Machine-readable error codestatusCode: HTTP status coderequestId: Request ID for debugging
TypeScript Support
The SDK is written in TypeScript and provides full type definitions.
import type {
VerifyKit2FAConfig,
SendOtpOptions,
SendOtpResult,
VerifyOtpResult,
ApiErrorResponse
} from '@verifykit.io/2fa';
// All types are exported and ready to use
const config: VerifyKit2FAConfig = {
apiKey: 'vk_live_...'
};
const result: SendOtpResult = await client.sendOtp('[email protected]');Advanced Features
Automatic Retries
The SDK automatically retries failed requests with exponential backoff:
const client = new VerifyKit2FA({
apiKey: 'vk_live_...',
maxRetries: 5 // Retry up to 5 times (default: 3)
});Retries are attempted for:
- Network errors
- Timeout errors
- Server errors (5xx)
- Rate limit errors (with appropriate delay)
Rate Limit Handling
The SDK automatically handles rate limits by:
- Detecting rate limit errors (429)
- Waiting for the
Retry-Afterduration - Retrying the request automatically
// The SDK handles this automatically
try {
const result = await client.sendOtp('[email protected]');
} catch (error) {
// Only throws if max retries exceeded
if (error instanceof RateLimitError) {
console.log('Still rate limited after retries');
}
}Debug Logging
Enable debug logging to see detailed request/response information:
const client = new VerifyKit2FA({
apiKey: 'vk_live_...',
debug: true
});
// Logs will show:
// - Request details
// - Retry attempts
// - Error informationCustom Timeouts
Configure request timeouts:
const client = new VerifyKit2FA({
apiKey: 'vk_live_...',
timeout: 60000 // 60 seconds
});OTP Security
VerifyKit 2FA codes are:
- SHA-256 hashed - Codes are never stored in plain text
- Single-use - Each code can only be verified once
- Auto-expiring - Codes expire after 10 minutes
- Rate limited - Maximum 5 verification attempts per code
Examples
Check out the examples directory for more usage examples:
- basic-usage.ts - Send and verify an OTP code
- error-handling.ts - Comprehensive error handling
Requirements
- Node.js >= 18.0.0
- TypeScript >= 5.0 (for TypeScript projects)
- VerifyKit Growth, Pro, or Unlimited plan
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
- Email: [email protected]
- Documentation: https://verifykit.io/docs
License
MIT (c) Nuno Miguel Duarte Unip. Lda
Made with care by the VerifyKit team
