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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@theprodigy/baileys-mysql-store

v1.1.0

Published

MySQL store implementation for Baileys WhatsApp library with LRU caching and batch processing

Downloads

19

Readme

Baileys MySQL Store

A comprehensive MySQL persistence solution for @whiskeysockets/baileys, providing both authentication state management and data storage with LRU caching and batch processing.

Credits

  • Authentication Implementation: Original MySQL auth implementation by @bobslavtriev
  • Enhancements: Updated to use connection pooling for better performance and resource management

Features

🔐 Authentication State Management

  • MySQL-based Auth Storage - Store authentication credentials and keys in MySQL
  • Multi-session Support - Handle multiple WhatsApp sessions with a single database
  • Automatic Table Creation - Database schema is created automatically
  • Connection Pooling - Efficient database connection management

💾 Data Store

  • MySQL Persistence - Store all WhatsApp data in MySQL database
  • LRU Caching - Multi-tiered caching strategy for optimal performance
  • Batch Processing - Efficient bulk database operations with transactions
  • Cache Warming - Proactive cache loading for frequently accessed data
  • Group Filtering - Exclude specific groups from tracking
  • Optimized Queries - Indexed queries and connection pooling

Installation

npm install @theprodigy/baileys-mysql-store baileys mysql2

Usage

Complete Example (Auth + Store)

import makeWASocket, { makeCacheableSignalKeyStore } from "baileys";
import { createAuth, createStore } from "@theprodigy/baileys-mysql-store";
import { createPool } from "mysql2/promise";
import pino from "pino";

const logger = pino({ level: "info" });

// Create MySQL connection pool (shared by both auth and store)
const pool = createPool({
  host: "localhost",
  user: "your_user",
  database: "whatsapp_db",
  password: "your_password",
  connectionLimit: 5
});

async function startWhatsApp() {
  const sessionId = "session_1";

  // Initialize MySQL auth state
  const { state, saveCreds } = await createAuth(pool, sessionId);

  // Initialize MySQL store
  const store = createStore(
    sessionId,
    pool,
    [], // Optional: array of group JIDs to skip tracking
    logger
  );

  // Create WhatsApp socket
  const sock = makeWASocket({
    auth: {
      creds: state.creds,
      keys: makeCacheableSignalKeyStore(state.keys, logger)
    },
    logger,
    printQRInTerminal: true
  });

  // Bind store to socket events
  await store.bind(sock.ev);

  // Save credentials on update
  sock.ev.on("creds.update", saveCreds);

  // Handle connection updates
  sock.ev.on("connection.update", (update) => {
    const { connection, lastDisconnect } = update;
    if (connection === "close") {
      console.log("Connection closed");
    } else if (connection === "open") {
      console.log("Connection opened");
    }
  });
}

startWhatsApp();

Auth Only

import { createAuth } from "@theprodigy/baileys-mysql-store";
import { createPool } from "mysql2/promise";

const pool = createPool({
  host: "localhost",
  user: "root",
  database: "whatsapp_db",
  password: "password"
});

const { state, saveCreds, removeCreds } = await createAuth(pool, "session_1");

// Use state.creds and state.keys with Baileys

Store Only

import { createStore } from "@theprodigy/baileys-mysql-store";
import { createPool } from "mysql2/promise";

const pool = createPool({
  host: "localhost",
  user: "root",
  database: "whatsapp_db",
  password: "password"
});

const store = createStore("session_1", pool, [], logger);
await store.bind(socket.ev);

API

createAuth(pool, session)

Creates a MySQL-based authentication state for Baileys.

Aliases: useMySQLAuthState (for backward compatibility)

Parameters:

  • pool (Pool): mysql2 connection pool
  • session (string): Session name to identify the connection (allows multi-sessions)

Returns: Object with:

  • state - Authentication state object with creds and keys
  • saveCreds() - Function to save credentials to database
  • clear() - Clear all auth data except credentials
  • removeCreds() - Remove all auth data including credentials
  • query(sql, values) - Execute custom SQL query

Database Table:

Automatically creates an auth table with columns:

  • session - Session identifier
  • id - Key identifier
  • value - JSON data

createStore(sessionId, pool, skippedGroups, logger)

Creates a new MySQL store instance for WhatsApp data.

Aliases: makeMySQLStore (for backward compatibility)

Parameters:

  • sessionId (string): Unique identifier for this session
  • pool (Pool): mysql2 connection pool
  • skippedGroups (string[]): Array of group JIDs to exclude from tracking. Groups in this list will not be stored in the database unless you are an admin/superadmin of the group. Useful for excluding large broadcast groups or communities you don't want to track. Default: []
  • logger (Logger): Pino logger instance (optional)

Returns: Store instance with methods:

  • bind(ev) - Bind to Baileys event emitter
  • loadMessage(id) - Load a message by ID
  • getAllChats() - Get all chats
  • getAllContacts() - Get all contacts
  • loadAllGroupsMetadata() - Load all group metadata
  • customQuery(query, params) - Execute custom SQL query
  • And many more...

Database Schema

The package automatically creates the following tables:

Authentication Tables

  • auth - Authentication credentials and keys (session, id, value)

Store Tables

  • messages - WhatsApp messages
  • chats - Chat conversations
  • contacts - Contact information
  • groups_metadata - Group metadata
  • users - User information

Features

Group Filtering

You can exclude specific groups from being tracked in the database using the skippedGroups parameter:

const store = createStore(
  "session_id",
  pool,
  [
    "[email protected]", // Large broadcast group
    "[email protected]" // Community you don't want to track
  ],
  logger
);

Important Notes:

  • Groups in the skippedGroups array will not be stored in the database
  • Exception: If you are an admin or superadmin of a skipped group, it will still be tracked
  • This is useful for excluding large communities, broadcast groups, or groups you don't need to monitor
  • Group JIDs typically end with @g.us

LRU Caching

  • Groups: 15-minute TTL
  • Contacts: 30-minute TTL
  • Message Types: 24-hour TTL

Batch Processing

  • Automatic batching of database writes
  • Configurable batch size and flush interval
  • Transaction support for data integrity

Environment Variables

MYSQL_HOST=localhost
MYSQL_USER=your_user
MYSQL_DATABASE=whatsapp_db
MYSQL_PASSWORD=your_password
MYSQL_PORT=3306
USER_SESSION=your_session_id

License

MIT

Acknowledgments

  • Built for use with Baileys - Lightweight full-featured WhatsApp Web + Multi-Device API
  • Original MySQL auth implementation by @bobslavtriev