A wrapper for the RapidAPI WhatsApp Data API with bulk checking and rate limiting support
npm install whatsapp-number-checkerA comprehensive wrapper for the RapidAPI WhatsApp Data API featuring advanced dual rate limiting, automatic retries, and bulk number verification with intelligent queue management.
- ✅ Dual Rate Limiting: Supports both window and monthly rate limits automatically extracted from API headers
- ✅ Automatic Retries: Intelligent rate limit error handling with exponential backoff
- ✅ Bulk Verification: Process multiple numbers with progress tracking and advanced options
- ✅ Real-time Monitoring: Track API usage through response headers analysis
- ✅ Required API Key: Mandatory API key validation in constructor
- ✅ TypeScript: Fully typed for enhanced developer experience
- ✅ Smart Queue: Automatic request management with dynamic adaptation
- ✅ Phone Validation: Built-in phone number validation using google-libphonenumber
``bash`
npm install whatsapp-number-checker
First, obtain an API key from RapidAPI WhatsApp Data.
⚠️ Important: The API key is required in the constructor and mandatory for accessing all methods.
`typescript
import { WhatsAppChecker } from 'whatsapp-number-checker';
const checker = new WhatsAppChecker({
apiKey: 'YOUR_RAPIDAPI_KEY_HERE', // REQUIRED
throwOnLimit: false, // Don't throw error after retries
timeout: 15000, // 15 second timeout
maxRetries: 3, // Retry up to 3 times on rate limit
retryDelay: 1000 // Base delay between retries
});
// Check a single number (with automatic retries)
const result = await checker.checkNumber('+1234567890');
console.log(result);
`
The system automatically handles two types of rate limits extracted from API headers:
, x-ratelimit-remaining, x-ratelimit-reset$3
- Limit: 5000 requests per month
- Headers: x-ratelimit-requests-limit, x-ratelimit-requests-remaining, x-ratelimit-requests-reset`typescript
const checker = new WhatsAppChecker({ apiKey: 'YOUR_API_KEY' });// Monitor current status for both limits
const rateLimitInfo = checker.getRateLimitInfo();
if (rateLimitInfo) {
console.log('Window Rate Limit:');
console.log(
Used: ${rateLimitInfo.used}/${rateLimitInfo.limit});
console.log( Remaining: ${rateLimitInfo.remaining});
console.log('Monthly Rate Limit:');
console.log( Used: ${rateLimitInfo.monthlyUsed}/${rateLimitInfo.monthlyLimit});
console.log( Remaining: ${rateLimitInfo.monthlyRemaining});
}// View current interval between requests (adapts automatically)
console.log(
Current interval: ${checker.getCurrentRateInterval()}ms);
`Bulk Verification with Advanced Options
`typescript
const numbers = ['+1234567890', '+0987654321', '+1122334455'];const bulkResult = await checker.checkBulk(numbers, {
onProgress: (completed, total, current) => {
console.log(
Progress: ${completed}/${total});
if (current.data && !('error' in current.data)) {
const data = current.data as any;
console.log(✅ ${current.number}: WhatsApp Contact: ${data.isWAContact});
} else {
console.log(❌ ${current.number}: Error);
}
},
onRateLimit: (rateLimitInfo) => {
console.log('Rate limit detected:');
console.log( Window: ${rateLimitInfo.used}/${rateLimitInfo.limit});
console.log( Monthly: ${rateLimitInfo.monthlyUsed}/${rateLimitInfo.monthlyLimit});
},
stopOnError: false
});console.log('Summary:', bulkResult.summary);
`Advanced Configuration
`typescript
const checker = new WhatsAppChecker({
apiKey: 'YOUR_API_KEY', // REQUIRED
throwOnLimit: true, // Throw RateLimitError after all retries
timeout: 15000,
maxRetries: 5, // Up to 5 retries on rate limit
retryDelay: 2000, // 2 second base delay (with exponential backoff)
baseURL: 'https://whatsapp-data1.p.rapidapi.com' // Custom URL
});try {
const result = await checker.checkNumber('+1234567890');
} catch (error) {
if (error.name === 'RateLimitError') {
console.log('Rate limit exhausted after retries:', error.rateLimitInfo);
}
}
`API Reference
$3
#### Constructor
`typescript
new WhatsAppChecker(config: WhatsAppCheckerConfig)
`#### Configuration
`typescript
interface WhatsAppCheckerConfig {
apiKey: string; // Your RapidAPI key (REQUIRED)
baseURL?: string; // API base URL
throwOnLimit?: boolean; // Throw error after retries (default: false)
timeout?: number; // Timeout in ms (default: 10000)
maxRetries?: number; // Max retries on rate limit (default: 3)
retryDelay?: number; // Base delay between retries in ms (default: 1000)
}
`#### Methods
#####
checkNumber(number: string): PromiseVerifies a single WhatsApp number with automatic retries and phone validation.
#####
checkBulk(numbers: string[], options?: BulkCheckOptions): PromiseVerifies multiple numbers with advanced options and progress tracking.
#####
getRateLimitInfo(): RateLimitInfo | nullGets current rate limit information extracted from API headers (both window and monthly).
#####
getCurrentRateInterval(): numberGets current interval between requests (adapts dynamically based on rate limits).
#####
getQueueLength(): numberGets number of pending requests in queue.
#####
clearQueue(): voidClears pending request queue.
#####
getLastResponseHeaders(): anyGets the last response headers for debugging purposes.
Response Types
$3
`typescript
interface CheckResult {
number: string;
data: WhatsappPersonResponse | WhatsappBusinessResponse | { error: string; success: null } | null;
error?: string;
rateLimitInfo?: RateLimitInfo;
}
`$3
`typescript
interface RateLimitInfo {
// Window rate limit (short-term)
remaining: number; // From x-ratelimit-remaining
limit: number; // From x-ratelimit-limit
reset: number; // From x-ratelimit-reset (timestamp)
used: number; // Calculated: limit - remaining
// Monthly rate limit (long-term)
monthlyRemaining: number; // From x-ratelimit-requests-remaining
monthlyLimit: number; // From x-ratelimit-requests-limit
monthlyReset: number; // From x-ratelimit-requests-reset (timestamp)
monthlyUsed: number; // Calculated: monthlyLimit - monthlyRemaining
}
`$3
#### Personal Account Response
`typescript
interface WhatsappPersonResponse {
_id: string;
number: string;
about: string;
countryCode: string;
isBlocked: boolean;
isBusiness: boolean;
isEnterprise: boolean;
isGroup: boolean;
isMe: boolean;
isMyContact: boolean;
isUser: boolean;
isWAContact: boolean; // Main indicator: Has WhatsApp
name: string;
phone: string;
profilePic: string;
pushname: string;
shortName: string;
type: string;
// ... other fields
}
`#### Business Account Response
`typescript
interface WhatsappBusinessResponse {
number: string;
isBusiness: boolean;
isEnterprise: boolean;
isUser: boolean;
isWAContact: boolean; // Main indicator: Has WhatsApp
name: string;
shortName: string;
verifiedLevel: number;
verifiedName: string;
countryCode: string;
phone: string;
businessProfile: BusinessProfile;
// ... other fields
}
`$3
`typescript
interface BulkCheckOptions {
onProgress?: (completed: number, total: number, current: CheckResult) => void;
onRateLimit?: (info: RateLimitInfo) => void;
stopOnError?: boolean;
maxRetries?: number;
}
`$3
`typescript
interface BulkCheckResult {
results: CheckResult[];
summary: {
total: number;
successful: number;
failed: number;
rateLimited: number;
};
rateLimitInfo?: RateLimitInfo;
}
`Error Handling and Retries
$3
`typescript
const checker = new WhatsAppChecker({
apiKey: 'YOUR_API_KEY',
maxRetries: 3,
throwOnLimit: true
});try {
const result = await checker.checkNumber('+1234567890');
} catch (error) {
if (error instanceof RateLimitError) {
console.log('Rate limit exhausted after 3 retries');
console.log('Limit info:', error.rateLimitInfo);
console.log('Window reset:', new Date(error.rateLimitInfo.reset * 1000));
console.log('Monthly reset:', new Date(error.rateLimitInfo.monthlyReset * 1000));
}
}
`$3
1. First attempt: Normal request
2. Rate limit detected: Extract info from headers
3. Calculate delay: Use reset time or exponential backoff
4. Retry: Up to maxRetries times
5. Fail or continue: Based on throwOnLimit setting
Window vs Monthly Handling:
- Window limit hit: Short retry delays, waits for window reset
- Monthly limit hit: Longer exponential backoff, doesn't wait for monthly reset
Best Practices
1. API Key: Always provide a valid API key
2. Rate Limiting: Trust the dynamic system, don't configure manual limits
3. Retries: Configure maxRetries based on your needs (3-5 recommended)
4. Monitoring: Use getRateLimitInfo() to monitor status
5. Bulk Operations: Use progress callbacks for user interfaces
6. Phone Format: Numbers can be with or without + prefix, the library handles formatting
7. Error Handling: Check for both API errors and request failures
Migration from Previous Version
If you were using the previous version with manual
rateLimit:`typescript
// BEFORE (v1.0.0)
const checker = new WhatsAppChecker({
apiKey: 'key',
rateLimit: 2 // Manual configuration
});// NOW (v1.1.0+)
const checker = new WhatsAppChecker({
apiKey: 'key', // REQUIRED
maxRetries: 3, // New: automatic retries
retryDelay: 1000 // New: delay between retries
// rateLimit is now extracted automatically from headers
// Supports both window and monthly limits
});
`Testing
$3
The library includes test scripts to validate functionality:
#### Single Number Test
`bash
Test a single number
npm run test-api [--verbose]Examples
npm run test-api "8ecfc15d5dmsh..." "+1234567890"
npm run test-api "8ecfc15d5dmsh..." "+59898297150" --verbose
`#### Bulk Test (Multiple Numbers)
`bash
Test multiple numbers
npm run test-bulk [PHONE_2] [...] [--verbose] [--stop-on-error]Examples
npm run test-bulk "8ecfc15d5dmsh..." "+1234567890" "+0987654321" "+1122334455"
npm run test-bulk "8ecfc15d5dmsh..." "+1234567890" "+0987654321" --verbose
npm run test-bulk "8ecfc15d5dmsh..." "+1234567890" "+0987654321" --stop-on-error --verbose
`Available flags:
-
--verbose, -v: Shows detailed information including rate limit headers
- --stop-on-error: Stops processing on first errorBulk test displays:
- ✅ Real-time progress for each number
- 📊 Detailed rate limit information (window and monthly)
- 📈 Final success/error statistics
- ⏱️ Total duration and request intervals
- 🚨 Rate limit alerts
Complete Examples
See:
-
examples.ts - Basic and advanced examples
- example-env.ts` - Usage with environment variablesContributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Submit a pull request
MIT