Baileys Redis Authentication State Handler
baileys-redis-auth is a specialized JavaScript/TypeScript library designed to provide robust Redis-based authentication state storage for Baileys, the popular WhatsApp Web API wrapper. Currently at version 2.0.1, this library primarily targets Baileys v7, with major releases typically coinciding with significant Baileys version updates, indicating a focused and stable release cadence. It differentiates itself by offering seamless session persistence, allowing Baileys applications to resume connections without repeated QR code scanning. Key features include flexible storage options, supporting both simple key-value pairs and the more efficient Redis Hashes (HSET) for optimized management of multiple Baileys sessions under distinct namespaces. This makes it particularly suitable for scalable applications requiring reliable session management, requiring Node.js 18+ and a running Redis server instance.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use CommonJS `require()` syntax with `baileys-redis-auth` which is an ESM-only package since v2.0.0.fixChange your import statements to ES module syntax (e.g., `import { useRedisAuthStateWithHSet } from 'baileys-redis-auth'`) and ensure your `package.json` contains `"type": "module"`. -
Error: Cannot find package 'baileys' or its corresponding type declarations.
cause The `baileys` package is a peer dependency but has not been installed in your project.fixInstall Baileys using your package manager: `npm install baileys` or `yarn add baileys`. -
Error: connect ECONNREFUSED <ip_address>:<port>
cause The application failed to connect to the Redis server, likely because the server is not running, is inaccessible, or the connection details are incorrect.fixVerify that your Redis server is active and reachable. Check the `host`, `port`, and `password` provided in your `redisOptions` object. -
TypeError: (0 , baileys_redis_auth__WEBPACK_IMPORTED_MODULE_0__.useRedisAuthStateWithHSet) is not a function
cause This often occurs in bundler environments (like Webpack or Vite) when mixing CommonJS and ESM or due to incorrect build configurations for ESM modules.fixEnsure your bundler is correctly configured to handle ES Modules. Verify `"type": "module"` in `package.json` and check your bundler's resolution/transpilation settings for `node_modules`.
Warnings
- breaking Version 2.0.0 and above are ESM-only modules. CommonJS (require()) syntax is no longer supported and will lead to runtime errors.
- breaking Baileys is now a peer dependency. It must be explicitly installed in your project alongside `baileys-redis-auth`.
- breaking The official Baileys package name changed from `@whiskeysockets/baileys` to `baileys` with its v7 release. This library aligns with the new package name.
- gotcha A running Redis server instance is a prerequisite. The library will fail to connect if Redis is not available or if connection details are incorrect.
Install
-
npm install baileys-redis-auth -
yarn add baileys-redis-auth -
pnpm add baileys-redis-auth
Imports
- useRedisAuthStateWithHSet
const { useRedisAuthStateWithHSet } = require('baileys-redis-auth')import { useRedisAuthStateWithHSet } from 'baileys-redis-auth' - deleteHSetKeys
const { deleteHSetKeys } = require('baileys-redis-auth')import { deleteHSetKeys } from 'baileys-redis-auth'
Quickstart
import { useRedisAuthStateWithHSet } from 'baileys-redis-auth'
import { RedisOptions } from 'ioredis'
import makeWASocket, { DisconnectReason } from 'baileys'
import { Boom } from '@hapi/boom'
// Define your Redis connection options
const redisOptions: RedisOptions = {
host: 'localhost',
port: 6379
// password: process.env.REDIS_PASSWORD ?? '', // Uncomment if your Redis has a password
}
// Define a unique session identifier for this Baileys session
const sessionId = 'my_baileys_session_example'
async function initializeBaileysWithHSet() {
const { state, saveCreds, redis: authRedisInstance } = await useRedisAuthStateWithHSet(
redisOptions,
sessionId,
console.log // Optional: pass logger for Redis connection events
)
authRedisInstance.on('connect', () =>
console.log(`Redis (from hook) connected for session: ${sessionId}`)
)
authRedisInstance.on('error', (err) =>
console.error(`Redis (from hook) error for session ${sessionId}:`, err)
)
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
})
sock.ev.on('creds.update', saveCreds)
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if (connection === 'close') {
const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
console.log('connection closed due to ', lastDisconnect?.error, ', reconnecting ', shouldReconnect)
// reconnect if not logged out
if (shouldReconnect) {
initializeBaileysWithHSet()
}
} else if (connection === 'open') {
console.log('opened connection')
}
})
// You can now use 'sock' for Baileys operations
console.log('Baileys initialized with Redis HSet state for session:', sessionId)
}
initializeBaileysWithHSet().catch(err => console.error('Failed to initialize Baileys:', err))