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

@msghub/sdk

v1.0.2

Published

Official TypeScript SDK for MsgHub.dev - WhatsApp & messaging APIs for developers

Readme

@msghub/sdk

Official TypeScript SDK for MsgHub.dev - WhatsApp & messaging APIs for developers.

Installation

npm install @msghub/sdk
# or
yarn add @msghub/sdk
# or
pnpm add @msghub/sdk

Note: This SDK uses axios for HTTP requests to ensure compatibility with both browser and Node.js environments. The axios dependency is automatically installed with the SDK.

Quick Start

import { MsgHubClient } from '@msghub/sdk';

// Initialize the client
const client = new MsgHubClient({
  apiKey: 'ba_your_api_key_here'
});

// Send a text message
const result = await client.messages.send('1234567890', {
  phone: '[email protected]',
  message: 'Hello, World!'
});

console.log('Message sent:', result.data);

Features

  • Type-safe: Full TypeScript support with comprehensive type definitions
  • Modern: Built with modern JavaScript/TypeScript features
  • Error handling: Custom error classes for better error handling
  • Promise-based: All methods return Promises
  • Tree-shakeable: Only import what you need
  • Well-documented: Comprehensive JSDoc comments

API Reference

Initialization

const client = new MsgHubClient({
  apiKey: 'ba_your_api_key_here', // Required: Your API key
  baseUrl: 'https://api.msghub.dev', // Optional: Default API URL
  timeout: 30000, // Optional: Request timeout in ms (default: 30000)
});

Account Management

Create a WhatsApp Account

const result = await client.accounts.create({
  phoneNumber: '1234567890',
  label: 'My Business Account',
  webhookUrl: 'https://your-server.com/webhook' // Optional
});

// If you provided webhookUrl, msgHub will auto-create the webhook and return the secret once.
// Save it securely and verify webhook calls with the X-Webhook-Secret header.
console.log('Webhook secret (save this):', result.data?.webhook?.secret);
console.log('Account number id:', result.data?.accountNumberId);

Webhooks (receive events on your server)

When your WhatsApp number receives a message, msgHub will POST the event to your webhook URL.

Every webhook request includes:

  • Header: X-Webhook-Secret: <your-secret>
  • JSON body: the forwarded event payload

Express example

import express from "express";
import {
  getWebhookEvent,
  getWebhookMessage,
  verifyWebhookSecret,
  type WebhookEnvelope,
  type WebhookMessageData,
} from "@msghub/sdk";

const app = express();
app.use(express.json());

app.post("/msghub/webhook", (req, res) => {
  if (!verifyWebhookSecret(req.headers, process.env.MSGHUB_WEBHOOK_SECRET!)) {
    return res.status(401).json({ error: "Invalid webhook secret" });
  }

  const payload = req.body as WebhookEnvelope<WebhookMessageData>;
  const event = getWebhookEvent(payload);

  if (event === "message" || event === "message.new") {
    const msg = getWebhookMessage(payload);
    const from = msg.from || msg.jid || msg.sender;
    const text = msg.body || msg.text || msg.message || "";
    console.log("Incoming message:", { from, text });
  }

  // Always ack fast
  return res.status(200).json({ received: true });
});

Next.js (App Router) route handler example

import {
  getWebhookEvent,
  verifyWebhookSecret,
  type WebhookEnvelope,
  type WebhookMessageData,
} from "@msghub/sdk";

export async function POST(req: Request) {
  // Works in Node.js runtime (default). If you run in Edge, make sure your env var is available.
  if (!verifyWebhookSecret(req.headers, process.env.MSGHUB_WEBHOOK_SECRET!)) {
    return Response.json({ error: "Invalid webhook secret" }, { status: 401 });
  }

  const payload = (await req.json()) as WebhookEnvelope<WebhookMessageData>;
  const event = getWebhookEvent(payload);
  // do your thing with `payload`

  return Response.json({ received: true, event });
}

Get Account Status

const status = await client.accounts.getStatus('1234567890');
console.log('Account status:', status.data);

List All Accounts

const accounts = await client.accounts.list();
console.log('Your accounts:', accounts.data);

Sending Messages

Send Text Message

const result = await client.messages.send('1234567890', {
  phone: '[email protected]',
  message: 'Hello, World!',
  reply_message_id: 'optional_message_id' // Optional: Reply to a message
});

Send Image

const result = await client.messages.sendImage('1234567890', {
  phone: '[email protected]',
  image: 'https://example.com/image.jpg', // or base64 string
  caption: 'Check this out!', // Optional
});

Send Video

const result = await client.messages.sendVideo('1234567890', {
  phone: '[email protected]',
  video: 'https://example.com/video.mp4',
  caption: 'Watch this video!', // Optional
});

Send Audio

const result = await client.messages.sendAudio('1234567890', {
  phone: '[email protected]',
  audio: 'https://example.com/audio.mp3',
  ptt: true // Optional: Mark as voice message
});

Send File

const result = await client.messages.sendFile('1234567890', {
  phone: '[email protected]',
  file: 'https://example.com/document.pdf',
  filename: 'document.pdf',
  caption: 'Here is the document' // Optional
});

Send Contact

const result = await client.messages.sendContact('1234567890', {
  phone: '[email protected]',
  contact: {
    displayName: 'John Doe',
    phoneNumber: '1234567890',
    organization: 'Acme Inc.' // Optional
  }
});

Send Location

const result = await client.messages.sendLocation('1234567890', {
  phone: '[email protected]',
  latitude: 40.7128,
  longitude: -74.0060,
  name: 'New York City', // Optional
  address: 'New York, NY, USA' // Optional
});

Send Link with Preview

const result = await client.messages.sendLink('1234567890', {
  phone: '[email protected]',
  url: 'https://example.com',
  text: 'Check out this website!' // Optional
});

Send Poll

const result = await client.messages.sendPoll('1234567890', {
  phone: '[email protected]',
  question: 'What is your favorite color?',
  options: [
    { name: 'Red' },
    { name: 'Blue' },
    { name: 'Green' }
  ],
  selectableCount: 1 // Optional: Allow multiple selections
});

Message Actions

Revoke Message

const result = await client.messages.revoke('1234567890', 'message_id');

Delete Message

const result = await client.messages.delete('1234567890', 'message_id');

React to Message

const result = await client.messages.react('1234567890', 'message_id', '👍');

Edit Message

const result = await client.messages.edit('1234567890', 'message_id', 'Updated message text');

Mark as Read

const result = await client.messages.markAsRead('1234567890', 'message_id');

Star/Unstar Message

// Star
await client.messages.star('1234567890', 'message_id');

// Unstar
await client.messages.unstar('1234567890', 'message_id');

Chat Management

List Chats

const chats = await client.chats.list('1234567890', {
  limit: 25, // Optional
  offset: 0 // Optional
});

Get Chat Messages

const messages = await client.chats.getMessages(
  '1234567890',
  '[email protected]',
  {
    limit: 50, // Optional
    offset: 0 // Optional
  }
);

Label Chat

const result = await client.chats.label(
  '1234567890',
  '[email protected]',
  ['important', 'customer']
);

Pin Chat

// Pin
await client.chats.pin('1234567890', '[email protected]', true);

// Unpin
await client.chats.pin('1234567890', '[email protected]', false);

User Information

Get User Info

const userInfo = await client.users.getInfo(
  '1234567890',
  '[email protected]' // Optional: omit to get your own info
);

Check if User is on WhatsApp

const result = await client.users.check('1234567890', '6289685028129');
console.log('Is on WhatsApp:', result.data?.is_on_whatsapp);

Get Business Profile

const profile = await client.users.getBusinessProfile(
  '1234567890',
  '[email protected]'
);

Error Handling

The SDK provides custom error classes for better error handling:

import {
  MsgHubClient,
  AuthenticationError,
  RateLimitError,
  NotFoundError,
  ValidationError,
  NetworkError,
  TimeoutError
} from '@msghub/sdk';

try {
  const result = await client.messages.send('1234567890', {
    phone: '[email protected]',
    message: 'Hello!'
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded. Retry after:', error.retryAfter);
  } else if (error instanceof NotFoundError) {
    console.error('Resource not found');
  } else if (error instanceof ValidationError) {
    console.error('Validation failed:', error.validationErrors);
  } else if (error instanceof NetworkError) {
    console.error('Network error:', error.message);
  } else if (error instanceof TimeoutError) {
    console.error('Request timeout');
  } else {
    console.error('Unknown error:', error);
  }
}

TypeScript Support

The SDK is written in TypeScript and provides full type definitions. All types are exported for your convenience:

import type {
  ClientOptions,
  SendMessageOptions,
  WhatsAppAccount,
  MessageResponse,
  Chat,
  ChatMessage,
  UserInfo,
  BusinessProfile
} from '@msghub/sdk';

Requirements

  • Node.js 14.0.0 or higher (or any modern browser)
  • TypeScript 5.0.0 or higher (for TypeScript projects)
  • axios (automatically installed with the SDK)

Browser & Node.js Compatibility

This SDK works in both browser and Node.js environments:

  • Browser: Works in all modern browsers (Chrome, Firefox, Safari, Edge)
  • Node.js: Works in Node.js 14+ (uses axios for HTTP requests)

The SDK automatically detects the environment and uses the appropriate HTTP client.

License

MIT