npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

whatsapp-number-checker

v1.1.0

Published

A wrapper for the RapidAPI WhatsApp Data API with bulk checking and rate limiting support

Readme

WhatsApp Number Checker

A comprehensive wrapper for the RapidAPI WhatsApp Data API featuring advanced dual rate limiting, automatic retries, and bulk number verification with intelligent queue management.

Features

  • 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

Installation

npm install whatsapp-number-checker

Setup

First, obtain an API key from RapidAPI WhatsApp Data.

⚠️ Important: The API key is required in the constructor and mandatory for accessing all methods.

Basic Usage

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);

Dual Rate Limiting System

The system automatically handles two types of rate limits extracted from API headers:

Window Rate Limit (Short-term)

  • Limit: 5 requests per window
  • Headers: x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset

Monthly Rate Limit (Long-term)

  • Limit: 5000 requests per month
  • Headers: x-ratelimit-requests-limit, x-ratelimit-requests-remaining, x-ratelimit-requests-reset
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

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

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

WhatsAppChecker

Constructor

new WhatsAppChecker(config: WhatsAppCheckerConfig)

Configuration

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): Promise<CheckResult>

Verifies a single WhatsApp number with automatic retries and phone validation.

checkBulk(numbers: string[], options?: BulkCheckOptions): Promise<BulkCheckResult>

Verifies multiple numbers with advanced options and progress tracking.

getRateLimitInfo(): RateLimitInfo | null

Gets current rate limit information extracted from API headers (both window and monthly).

getCurrentRateInterval(): number

Gets current interval between requests (adapts dynamically based on rate limits).

getQueueLength(): number

Gets number of pending requests in queue.

clearQueue(): void

Clears pending request queue.

getLastResponseHeaders(): any

Gets the last response headers for debugging purposes.

Response Types

CheckResult

interface CheckResult {
  number: string;
  data: WhatsappPersonResponse | WhatsappBusinessResponse | { error: string; success: null } | null;
  error?: string;
  rateLimitInfo?: RateLimitInfo;
}

RateLimitInfo (Dual Rate Limits)

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
}

WhatsApp API Response Types

Personal Account Response

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

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
}

BulkCheckOptions

interface BulkCheckOptions {
  onProgress?: (completed: number, total: number, current: CheckResult) => void;
  onRateLimit?: (info: RateLimitInfo) => void;
  stopOnError?: boolean;
  maxRetries?: number;
}

BulkCheckResult

interface BulkCheckResult {
  results: CheckResult[];
  summary: {
    total: number;
    successful: number;
    failed: number;
    rateLimited: number;
  };
  rateLimitInfo?: RateLimitInfo;
}

Error Handling and Retries

RateLimitError with Automatic Retries

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));
  }
}

Retry Strategy

  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:

// 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

Test Scripts

The library includes test scripts to validate functionality:

Single Number Test

# Test a single number
npm run test-api <API_KEY> <PHONE_NUMBER> [--verbose]

# Examples
npm run test-api "8ecfc15d5dmsh..." "+1234567890"
npm run test-api "8ecfc15d5dmsh..." "+59898297150" --verbose

Bulk Test (Multiple Numbers)

# Test multiple numbers
npm run test-bulk <API_KEY> <PHONE_1> [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 error

Bulk 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 variables

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Submit a pull request

License

MIT