How to host a WhatsApp bot 24/7 with Baileys: sessions, pairing code and the 20,000-file problem

, developer of Bot-Hosting

Baileys lets a Node.js bot connect to WhatsApp as a linked device, like WhatsApp Web, with no browser to keep alive. WhatsApp bots, Baileys ones included, are allowed on Bot-Hosting on every plan, the free one too.

This guide covers how to run a Baileys bot 24/7 without losing the session: linking by QR code or pairing code, a small bot we tested, why session folders grow to tens of thousands of files, and how to keep them small.

What Baileys is

Baileys is a Node.js library that opens a WebSocket to WhatsApp’s servers and registers your bot as a linked device, exactly like WhatsApp Web on a laptop. There is no browser and no Chromium: the README notes that this saves about half a gigabyte of RAM compared with browser-based libraries.

The official package is @whiskeysockets/baileys on npm. On 30 November 2026, its latest tag points to 7.0.0-rc14 (published 29 July 2026) and its legacy tag to 6.7.24. Version 7 is a release candidate, so pin the exact version: a caret range would pull the next RC the day it lands, with whatever it changes. Version 7 is ESM only and needs Node.js 20 or later.

Diagram: your phone links the bot as a device; WhatsApp servers relay messages to the bot over a WebSocket; the bot writes its credentials and Signal keys to a session store.

The important consequence: after linking, the session store is your WhatsApp login. Whoever has a copy can read and send messages as you, without your phone. Keep that in mind for the rest of this guide.

A minimal WhatsApp bot (tested)

package.json:

{
  "name": "whatsapp-bot",
  "private": true,
  "type": "module",
  "main": "index.js",
  "engines": { "node": ">=20" },
  "dependencies": {
    "@whiskeysockets/baileys": "7.0.0-rc14",
    "pino": "9.14.0",
    "qrcode-terminal": "0.12.0"
  }
}

index.js:

import { rm } from 'node:fs/promises';
import makeWASocket, { Browsers, DisconnectReason, useMultiFileAuthState } from '@whiskeysockets/baileys';
import pino from 'pino';
import qrcode from 'qrcode-terminal';

const AUTH_DIR = process.env.AUTH_DIR ?? 'auth';
const PAIRING_NUMBER = process.env.PAIRING_NUMBER; // digits only, with country code
const logger = pino({ level: process.env.LOG_LEVEL ?? 'warn' });
let retries = 0;

async function start() {
    const { state, saveCreds } = await useMultiFileAuthState(AUTH_DIR);
    const sock = makeWASocket({ auth: state, logger, browser: Browsers.ubuntu('Chrome'), markOnlineOnConnect: false });
    sock.ev.on('creds.update', saveCreds);
    let pairingAsked = false;

    sock.ev.on('connection.update', async ({ connection, lastDisconnect, qr }) => {
        if (qr && !PAIRING_NUMBER) qrcode.generate(qr, { small: true });
        if (qr && PAIRING_NUMBER && !pairingAsked && !sock.authState.creds.registered) {
            pairingAsked = true;
            const code = await sock.requestPairingCode(PAIRING_NUMBER);
            console.log(`Pairing code: ${code} (on your phone: Linked devices > link with phone number)`);
        }
        if (connection === 'open') {
            retries = 0;
            console.log('Connected as', sock.user?.id);
        }
        if (connection === 'close') {
            const code = lastDisconnect?.error?.output?.statusCode;
            if (code === DisconnectReason.loggedOut) {
                // The device was removed in WhatsApp: start over with a new QR or pairing code
                console.error('Logged out, clearing the session');
                await rm(AUTH_DIR, { recursive: true, force: true });
                return start();
            }
            const delay = Math.min(30_000, 2_000 * 2 ** retries++);
            console.log(`Connection closed (${code}), reconnecting in ${delay / 1000}s`);
            setTimeout(start, delay);
        }
    });

    sock.ev.on('messages.upsert', async ({ messages, type }) => {
        if (type !== 'notify') return;
        for (const m of messages) {
            if (m.key.fromMe || !m.message) continue;
            const text = m.message.conversation ?? m.message.extendedTextMessage?.text ?? '';
            if (text.trim().toLowerCase() === '!ping') {
                await sock.sendMessage(m.key.remoteJid, { text: 'pong' }, { quoted: m });
            }
        }
    });
}

start();

It answers !ping with pong, ignores its own messages, saves credentials on every change, reconnects with a growing delay (2, 4, 8 seconds, up to 30), and starts over cleanly if you remove the device from your phone.

What we tested on 30 November 2026: we ran it in the same Node.js 24 image our panel uses and on Node.js 22, until WhatsApp sent a QR code. The process used about 140 MB of RAM at that point. We did not link a real phone for this article, so the steps after linking come from the Baileys documentation and source, not from our own run.

QR code or pairing code

Both link the same way; they differ in what you do with your hands.

  • QR code. Leave PAIRING_NUMBER unset. The bot prints a QR code in the console. On your phone, open Linked devices, tap Link a device and scan it. In Baileys 7 the first QR code lives 60 seconds, the next ones 20, so keep the console open.
  • Pairing code. Set PAIRING_NUMBER to the bot’s own number, digits only with the country code: 447700900123, not +44 7700 900123. The bot prints an 8-character code. On your phone, start linking a device, choose the option to link with a phone number, and type it.

On a server, the pairing code is usually easier: a QR code drawn in a web console can be hard to scan. Either way, it is a one-time step. After that the bot reconnects on its own, and your phone can be off. Use a number dedicated to the bot rather than your personal one, so its chats stay apart from yours.

Where the session lives, and why it grows to 20,000 files

useMultiFileAuthState('auth') writes the session as one small JSON file per key in the auth folder. Baileys’ README calls it a guide for writing your own store and recommends a SQL or NoSQL database “in any production grade system”. Most bots ship it as it is.

FileWhat it isGrows with
creds.jsonyour identity and loginnever, one file
pre-key-*.jsonone-time keys others use to start a session with you812 at linking, used ones are removed
session-*.jsonan encryption session per contact deviceevery person who messages the bot
sender-key-*.jsona key per group and per member deviceevery group the bot is in, fastest of all
app-state-sync-*, device-list-*, lid-mapping-*, tctoken-*sync and lookup datacontacts and devices

A freshly linked Baileys 7 bot already has 813 files: 812 pre-keys plus creds.json. Then every contact device and every group member adds files, and nothing removes the old ones. When we counted on 21 September 2026, about 70 WhatsApp bots on our fleet had more than 20,000 session files each. The largest folder held 684,708 files for 43 WhatsApp accounts.

Chart, log scale: 813 files just after linking; four servers on our fleet with 208,723, 316,131, 581,166 and 684,708 files; about 70 servers above 20,000 files.

Why it matters, even with free disk space:

  • Every restart, backup and copy has to walk the folder. Hundreds of thousands of tiny files are slow to read, archive and restore, whatever their total size.
  • On a shared host, it slows the disk accounting. On our fleet, the node agent’s disk usage scan has to look at every file, and its cost grows with the file count. Keeping session folders small keeps restarts fast.
  • Multi-account bots multiply it. One folder per number, each growing on its own.

Clean up a bloated session folder safely

Two kinds of files are safe to drop when nobody has used them for a while: session-* and sender-key-*. If a contact or a group comes back, the first message may fail to decrypt, and WhatsApp’s retry mechanism has the sender rebuild the session. Never delete creds.json (that logs the bot out), pre-key-* or app-state-sync-key-*.

Run the cleanup before Baileys starts, never while it is writing. prune-session.js:

import { readdir, stat, unlink } from 'node:fs/promises';
import { join } from 'node:path';

// Signal sessions and group sender keys can be rebuilt by WhatsApp's retry mechanism.
// creds.json, pre-keys and app-state keys cannot: never touch them.
const PRUNABLE = /^(session|sender-key)-.+.json$/;

export async function pruneSession(dir, days = 30) {
    const cutoff = Date.now() - days * 86_400_000;
    let removed = 0;
    let names = [];
    try {
        names = await readdir(dir);
    } catch {
        return 0; // no session yet
    }
    for (const name of names) {
        if (!PRUNABLE.test(name)) continue;
        const file = join(dir, name);
        if ((await stat(file)).mtimeMs < cutoff) {
            await unlink(file);
            removed++;
        }
    }
    console.log(`Session cleanup: removed ${removed} of ${names.length} files (untouched for ${days}+ days)`);
    return removed;
}

Then in index.js, add import { pruneSession } from './prune-session.js'; at the top and replace the last line with:

await pruneSession(AUTH_DIR, 30);
start();

Every restart now drops sessions and group keys untouched for 30 days. We tested the function on a folder of fake session files with old and new dates: it removed only the old session-*, sender-key-* and sender-key-memory-* files and kept creds.json, the pre-keys and the app-state keys. This is a maintenance trade-off, not a procedure from the Baileys documentation, so download a backup of the folder before the first run.

Better: keep the session in SQLite

The cleaner fix is the one the README recommends: a database. With Node.js 22.13 or later (24 recommended; 22 prints an “experimental” warning), the built-in node:sqlite module needs no extra package. auth-sqlite.js:

import { DatabaseSync } from 'node:sqlite';
import { BufferJSON, initAuthCreds, proto } from '@whiskeysockets/baileys';

// Baileys auth state in one SQLite file instead of thousands of JSON files.
export function useSqliteAuthState(file) {
    const db = new DatabaseSync(file);
    db.exec('PRAGMA journal_mode = WAL; CREATE TABLE IF NOT EXISTS auth (k TEXT PRIMARY KEY, v TEXT NOT NULL)');
    const get = db.prepare('SELECT v FROM auth WHERE k = ?');
    const put = db.prepare('INSERT INTO auth (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v');
    const del = db.prepare('DELETE FROM auth WHERE k = ?');
    const read = (k) => {
        const row = get.get(k);
        return row ? JSON.parse(row.v, BufferJSON.reviver) : null;
    };
    const write = (k, v) => put.run(k, JSON.stringify(v, BufferJSON.replacer));

    const creds = read('creds') ?? initAuthCreds();
    return {
        state: {
            creds,
            keys: {
                get: async (type, ids) => {
                    const out = {};
                    for (const id of ids) {
                        let value = read(`${type}:${id}`);
                        if (type === 'app-state-sync-key' && value) {
                            value = proto.Message.AppStateSyncKeyData.fromObject(value);
                        }
                        out[id] = value;
                    }
                    return out;
                },
                set: async (data) => {
                    db.exec('BEGIN');
                    try {
                        for (const type in data) {
                            for (const id in data[type]) {
                                const value = data[type][id];
                                if (value) write(`${type}:${id}`, value);
                                else del.run(`${type}:${id}`);
                            }
                        }
                        db.exec('COMMIT');
                    } catch (err) {
                        db.exec('ROLLBACK');
                        throw err;
                    }
                },
            },
        },
        saveCreds: async () => write('creds', creds),
    };
}

In index.js, import it and replace the useMultiFileAuthState line:

const { state, saveCreds } = useSqliteAuthState('auth.db');

Same data, one file, written in a transaction. We tested a full round trip (credentials, keys with binary data, app-state keys, deletions, reopening the database as after a restart) and ran the bot with it to the QR code on Node.js 24. Switching stores means linking the device once more, unless you write a script to import the old folder.

One thing to know when you move or back up the database: SQLite in WAL mode keeps recent writes in auth.db-wal and auth.db-shm. Copy the three files together, or stop the bot first. On our fleet, a database copied without its -wal file is reported as “malformed”.

For several bots sharing one store, the same twenty lines work against PostgreSQL, MySQL or Redis. If you pick MongoDB, keep the connection pool small: MongoDB uses one thread per connection, and containers on our platform have a process limit.

SESSION_ID bots: treat it like a password

Many ready-made “MD” bots ask for a SESSION_ID instead of showing a QR code. It is usually your credentials, encoded into one long string, generated by linking the device somewhere else first.

  • Store it as a secret. On Bot-Hosting, add it in the Environment tab and tick Secret, so it is masked in the panel. Never commit it, never paste it in a public repository or a support ticket.
  • Be careful where it comes from. If a third-party website does the linking for you and hands you the SESSION_ID, that website had your login. Prefer bots that let you pair in your own console.
  • If it leaks, revoke it. On your phone, open Linked devices and log out the bot’s device. The string stops working immediately. Link again to get a new one.

RAM, restarts and logs on a 24/7 host

RAM. The minimal bot above sat around 140 MB in our test, so the Free plan’s 256 MB is enough for a small bot. Feature-heavy MD bots that make stickers, download videos or run ffmpeg need more: watch the memory graph for a few days and size from that, not from a guess.

Restarts. Baileys reconnects on its own after a network drop; that is the connection === 'close' branch. If the process itself crashes, Bot-Hosting restarts it. The session survives both, because it is on the deployment’s persistent disk.

Open files. A bot that holds many connections can hit the default limit of 1,024 open files. On our fleet, “getaddrinfo … System error” crashes usually turn out to be exactly that, not a DNS problem.

Logs. Everything the bot prints shows in the Console. Set LOG_LEVEL=info in the Environment tab when you debug; Baileys’ own logs are verbose, so go back to warn afterwards.

Deploy a WhatsApp bot on Bot-Hosting

  1. Sign up on Bot-Hosting and create a New deployment: Application, then Node.js.
  2. Source: GitHub if your code is in a repository, or Archive with a .zip of package.json, index.js and the helper files. Do not include node_modules or the auth folder.
  3. The entry file defaults to index.js. Dependencies are installed from package.json at each start.
  4. In the Environment tab, add PAIRING_NUMBER if you want a pairing code, and any secret your bot needs (tick Secret).
  5. Start it, read the QR code or the pairing code in the Console, and link from your phone. Connected as ... means it is online.

On the Free plan, the deployment never sleeps but has to be renewed by hand every 4 days (how renewal works). The Node.js hosting page covers the runtime, and WhatsApp bot hosting covers plans and limits for WhatsApp bots.

Deploying a ready-made bot from GitHub instead? Before you start it, check four things: the source code is readable rather than obfuscated, the Baileys version is pinned, you can pair in your own console, and the command list has no “bug”, spam or mass-messaging features.

What you can and cannot run

Our terms forbid spam and unsolicited mass messaging, and we remove bots that do it. In practice:

  • No bulk senders, auto-dialers or “broadcast to a list” bots aimed at people who did not opt in.
  • No “bug” or crash bots that send messages designed to freeze or crash other people’s WhatsApp.
  • No scraping of groups or contact lists to harvest numbers.

Helpful bots, games, group moderation, reminders and personal assistants for people who chose to use them are fine, on every plan.

Sources

Checked on 30 November 2026:

  • Baileys README, for the pairing code and useMultiFileAuthState notes; the @whiskeysockets/baileys package on npm for versions and tags.
  • Baileys 7.0.0-rc14 source, Defaults/index.js (812 initial pre-keys) and Socket/socket.js (QR code timeouts).
  • Node.js node:sqlite documentation.
  • Our own tests on 30 November 2026 and fleet counts from 21 September 2026.