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

@nevi-dev/sqlite-auth

v1.0.0

Published

Proveedor de estado de autenticación SQLite de alto rendimiento para @whiskeysockets/baileys

Readme

@nevi-dev/sqlite-auth

Developed with ❤️ by Nevi Dev

English | Español


English

🌍 The Problem with Multi-File Auth

By default, Baileys uses useMultiFileAuthState, which creates a separate JSON file for every single pre-key, session, and sender-key. When running a bot for a long time—or hosting multiple sub-bots—this behavior generates thousands of tiny files.

This causes serious issues:

  • High Disk I/O: Constantly reading and writing thousands of files degrades server performance.
  • File System Bloat: Cloud providers or OS file systems can hit inode limits, crashing the server.
  • Slow Backups/Deletions: Deleting or moving a session folder with 50,000 JSON files can take minutes.

💡 The Solution by Nevi Dev

@nevi-dev/sqlite-auth completely replaces the file system layer. It intercepts Baileys read/write operations and pipes them directly into a single, highly-optimized SQLite database file powered by better-sqlite3.


🌟 Features

  • Single-File Storage: Credentials and keys live safely inside one .db file per bot.
  • WAL Mode Natively Enabled: Uses SQLite's Write-Ahead Logging. This allows concurrent reads and writes without blocking the Node.js event loop, ensuring peak performance even under heavy message load.
  • Smart Legacy Purge: Before initializing the database, it automatically scans and wipes out old JSON files (pre-key-, sender-key-, etc.) to free up space.
  • Agnostic & Scalable: Perfectly tailored for multi-bot managers, panels, or distributed worker threads.

🚀 Installation

npm install @nevi-dev/sqlite-auth better-sqlite3

Note: @whiskeysockets/baileys must be installed in your project.

🛠️ Basic Usage

import makeWASocket from '@whiskeysockets/baileys';
import { useSQLiteAuthState } from '@nevi-dev/sqlite-auth';

// Initialize the SQLite session state
const { state, saveCreds } = useSQLiteAuthState('./sessions/main_bot', {
    dbName: 'auth.db',       // Optional: Database filename (Default: auth.db)
    cleanOldFiles: true     // Optional: Automatically purges legacy JSON files (Default: true)
});

// Create the Baileys connection using the SQLite state
const sock = makeWASocket({
    auth: state,            
    printQRInTerminal: true
});

// Save credentials automatically on updates
sock.ev.on('creds.update', saveCreds);

🤖 Advanced Multi-Bot Control (System Registry)

If you manage dynamic sub-bots or multiple client instances, you can spin up a central database using createManagerDatabase to keep track of every connection state.

import { createManagerDatabase } from '@nevi-dev/sqlite-auth';

// Initialize the central controller DB
const systemDb = createManagerDatabase({
    dbPath: './sessions/system.db',   // Optional: Custom path for system db
    tableName: 'bot_registry'          // Optional: Custom table name
});

// Example: Inserting or updating a sub-bot status using better-sqlite3
systemDb.prepare('INSERT OR REPLACE INTO bot_registry (id, jid, status, metadata) VALUES (?, ?, ?, ?)')
    .run('subbot_99', '[email protected]', 'online', JSON.stringify({ plan: 'Premium' }));

Español

🌍 El Problema con el Estado Multi-Archivo

Por defecto, Baileys utiliza useMultiFileAuthState, el cual crea un archivo JSON independiente para cada pre-key, sesión y llave de remitente. Al mantener un bot activo por mucho tiempo—o al alojar múltiples sub-bots— este comportamiento genera miles de archivos diminutos.

Esto provoca fallos críticos:

  • Alto Impacto en I/O de Disco: Leer y escribir constantemente miles de archivos degrada el rendimiento del servidor.
  • Saturación del Sistema de Archivos: Los servidores en la nube pueden agotar sus límites de nodos-i (inodes), congelando el sistema.
  • Lentitud en Backups/Eliminaciones: Borrar una sola carpeta de sesión con 50,000 JSONs puede tomar minutos enteros de procesamiento.

💡 La Solución de Nevi Dev

@nevi-dev/sqlite-auth reemplaza por completo la capa del sistema de archivos. Intercepta las operaciones de lectura y escritura de Baileys y las redirige directamente hacia un único archivo de base de datos SQLite, optimizado mediante better-sqlite3.


🌟 Características

  • Almacenamiento en un Solo Archivo: Las credenciales y llaves residen de forma segura dentro de un único archivo .db por bot.
  • Modo WAL Activado Nativamente: Utiliza el método Write-Ahead Logging de SQLite. Esto permite lecturas y escrituras concurrentes instantáneas sin bloquear el bucle de eventos de Node.js, garantizando fluidez ante ráfagas masivas de mensajes.
  • Purga Inteligente de Basura: Antes de inicializar la base de datos, escanea y elimina archivos JSON antiguos (pre-key-, sender-key-, etc.) para liberar espacio en disco inmediatamente.
  • Agnóstico y Escalable: Diseñado meticulosamente para integrarse con gestores multi-bots, paneles web o hilos de trabajo (worker_threads).

🚀 Instalación

npm install @nevi-dev/sqlite-auth better-sqlite3

Nota: Debes tener @whiskeysockets/baileys instalado en tu proyecto.

🛠️ Uso Básico

import makeWASocket from '@whiskeysockets/baileys';
import { useSQLiteAuthState } from '@nevi-dev/sqlite-auth';

// Inicializa el estado de la sesión en SQLite
const { state, saveCreds } = useSQLiteAuthState('./sessions/main_bot', {
    dbName: 'auth.db',       // Opcional: Nombre del archivo de base de datos (Por defecto: auth.db)
    cleanOldFiles: true     // Opcional: Borra automáticamente archivos JSON heredados de Baileys (Por defecto: true)
});

// Crea la conexión del socket de Baileys pasándole el estado
const sock = makeWASocket({
    auth: state,            
    printQRInTerminal: true
});

// Escucha las actualizaciones de credenciales y guárdalas en SQLite
sock.ev.on('creds.update', saveCreds);

🤖 Control Avanzado Multi-Bot (Registro de Sistema)

Si estás construyendo un panel multi-cuentas o un sistema dinámico de sub-bots, utiliza createManagerDatabase para centralizar y monitorear los estados de tus instancias desde un solo lugar:

import { createManagerDatabase } from '@nevi-dev/sqlite-auth';

// Inicializa una base de datos central de control
const systemDb = createManagerDatabase({
    dbPath: './sessions/system.db',   // Opcional: Ruta personalizada para la DB del sistema
    tableName: 'bot_registry'          // Opcional: Nombre personalizado para la tabla
});

// Ejemplo: Insertar o actualizar el estado de un sub-bot usando consultas nativas de better-sqlite3
systemDb.prepare('INSERT OR REPLACE INTO bot_registry (id, jid, status, metadata) VALUES (?, ?, ?, ?)')
    .run('subbot_99', '[email protected]', 'online', JSON.stringify({ plan: 'Premium' }));

⚙️ Configuration Options / Opciones de Configuración

useSQLiteAuthState(sessionDir, options)

| Option / Opcional | Type / Tipo | Default / Defecto | Description / Descripción | | :--- | :--- | :--- | :--- | | dbName | String | 'auth.db' | The name of the SQLite file inside the session folder. / El nombre del archivo SQLite dentro de la carpeta de sesión. | | cleanOldFiles | Boolean | true | Deletes legacy JSON files from Baileys if they exist. / Elimina los archivos JSON antiguos de Baileys si existen. |

createManagerDatabase(options)

| Option / Opcional | Type / Tipo | Default / Defecto | Description / Descripción | | :--- | :--- | :--- | :--- | | dbPath | String | './sessions/system.db' | Global path to store the manager database. / Ruta global para almacenar la base de datos del administrador. | | tableName | String | 'bot_registry' | Table name inside the manager database. / Nombre de la tabla dentro de la base de datos del administrador. |


📄 License / Licencia

Distributed under the MIT License. Created and maintained by Nevi Dev.
Distribuido bajo la Licencia MIT. Creado y mantenido por Nevi Dev.