#WhatsApp Web.js Session Reconnection Issue

23 messages · Page 1 of 1 (latest)

nocturne bronze
#

Environment

  • whatsapp-web.js version: 1.34.2 (also tested with 1.33.2)
  • puppeteer version: 22.15.0 (also tested with 19.7.5)
  • Node.js version: 18 (Docker) / 20 (local compilation)
  • Operating System: Ubuntu 22.04 (Docker), Windows 11 (local testing)
  • Browser: Chromium (puppeteer bundled) and Google Chrome stable

Problem Description

Sessions authenticate successfully but never reach the "ready" state after container/server restart. This only affects reconnection - initial connection works perfectly.

Working: Initial Connection (2 Months ago) ✅

  1. Session created with client.initialize()
  2. qr event fires → QR code generated
  3. User scans QR code
  4. authenticated event fires
  5. ready event fires
  6. Messages can be sent successfully

Failing: Reconnection After Restart ❌

  1. Server/container restarts
  2. Session loads from saved data (LocalAuth)
  3. authenticated event fires
  4. ready event NEVER fires
  5. window.Store remains undefined
  6. Attempting to send messages fails with: TypeError: Cannot read properties of undefined (reading 'getChat')

Reproduction Steps

  1. Create a new session:
const client = new Client({
  authStrategy: new LocalAuth({
    clientId: sessionId,
    dataPath: path.join(SESSIONS_DIR, sessionId),
  }),
  puppeteer: {
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-dev-shm-usage",
      "--disable-accelerated-2d-canvas",
      "--no-first-run",
      "--disable-extensions",
      "--disable-gpu",
    ],
    headless: true,
    executablePath: process.env.DOCKER_ENV === 'true'
      ? '/usr/bin/google-chrome-stable'
      : undefined,
  },
  takeoverOnConflict: true,
});

client.initialize();
  1. Scan QR code → Works perfectly, ready event fires
  2. Restart server/container
  3. Session loads automatically but ready never fires

In case you're reading , message adding rest of information is on demand

#

What We've Tried

❌ Update to whatsapp-web.js 1.34.2

  • No improvement in reconnection behavior

❌ Use Google Chrome instead of Chromium

  • Added executablePath: '/usr/bin/google-chrome-stable' in Docker
  • Still fails on reconnection

❌ Update puppeteer to 22.15.0 + Remove webVersionCache

  • Updated from puppeteer 19.7.5 to 22.15.0
  • Delete webVersionCache.json on session load to force WhatsApp Web update
  • Still fails on reconnection

✅ Applied PR #3972 (Testing)

Applied the fix from https://github.com/pedroslopez/whatsapp-web.js/pull/3972 that preloads WAWebProfileDrawerLoadableRequireBundle:

Modified node_modules/whatsapp-web.js/src/Client.js (line 220):

if (isCometOrAbove) {
    await this.pupPage.evaluate(async () => {
        await window.require("WAWebProfileDrawerLoadableRequireBundle").requireBundle()
    });
    await this.pupPage.evaluate(ExposeStore);
} else {

✅ Applied PR #3975 (Testing)

Applied the fix from https://github.com/pedroslopez/whatsapp-web.js/pull/3975/files that adds error handling for setPushname:

Modified node_modules/whatsapp-web.js/src/util/Injected/Store.js (line 110):

window.Store.Settings = {
    ...window.require('WAWebUserPrefsGeneral'),
    ...window.require('WAWebUserPrefsNotifications'),
    setPushname: (() => {
        try {
            const module = window.require('WAWebSetPushnameConnAction');
            return module && module.setPushname ? module.setPushname : async () => { return false; };
        } catch (e) {
            // Module not available, return a no-op function
            return async () => { return false; };
        }
    })()
};

Status: Currently testing these fixes, but issue persists.

#

Key Observations

  1. The problem is specific to reconnection - initial connection always works
  2. Session data is preserved correctly - authentication succeeds
  3. window.Store injection seems to complete - no errors in that stage
  4. The ready event simply never fires - client gets stuck after authentication
  5. No error messages - the process just hangs silently without reaching ready state

Diagnostic Logs

Initial Connection (Working)

Creando nuevo cliente de WhatsApp para la sesión ID: abc-123
Session abc-123: qr event - QR generado
Session abc-123: authenticated
Session abc-123: ready

Reconnection (Failing)

Loading existing session: abc-123
Inicializando cliente de WhatsApp para la sesión ID: abc-123
Session abc-123: authenticated
[... nothing more happens ...]

Questions for the Community

  1. Is this a known issue with LocalAuth strategy in multi-restart scenarios?
  2. Are there any additional events we should be listening to that might indicate why ready isn't firing?
  3. Should we implement a timeout to force-restart the session if ready doesn't fire within X seconds?
  4. Is there a way to debug what's happening inside WhatsApp Web between authenticated and ready?
  5. Would switching to a different auth strategy (like RemoteAuth) help with reconnection reliability?
#

It's helpful to mention that the docker image developed 2 months ago doesn't fail to reconnect the session after restarting the container. The image works well, can it be an OS related issue?

midnight cosmos
#

You need to debug it more, because everything is working fine

solemn bridge
#

I have the same issue, and below are my versions -

"axios": "^1.5.0",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-rate-limit": "^6.10.0",
"form-data": "^4.0.4",
"helmet": "^7.0.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^7.5.0",
"multer": "^1.4.5-lts.1",
"node-cron": "^3.0.2",
"qrcode": "^1.5.3",
"qs": "^6.14.0",
"uuid": "^9.0.0",
"whatsapp-web.js": "github:pedroslopez/whatsapp-web.js#main"

hazy cosmos
hazy cosmos
#

@nocturne bronzeplease test #3972 again

#

I made an update

nocturne bronze
#

greetings and sorry for the late response. I have tried checking the window. Still not working, as the page is not loading after event "authenticated" .

I have tried again #3972, but didn't help me neither

#

Errors found

nocturne bronze
#

update, my 2 months old docker image doesn't reconnect the session
Maybe problem is our event handler isn't configured right. My code snippet (as soon as server starts):

const clients = new Map<string, Client>();

// Cola para gestionar la inicialización de sesiones de WhatsApp
const initQueue = new Queue(
  (task: { sessionId: string; isNewSession: boolean }, done: (error: any, result?: any) => void) => {
    const { sessionId, isNewSession } = task;
    console.log(`Procesando nueva sesión en cola con ID: ${sessionId}`);
    const client = initWhatsAppClient(sessionId, isNewSession); // Inicializa cliente de WhatsApp
    clients.set(sessionId, client); // Almacena el cliente en el mapa
    done(null, sessionId); // Completa la tarea en la cola
  },
  { concurrent: parseInt(process.env.MAX_CONCURRENT_SESSIONS || "4") } // Número máximo de peticiones simultáneas.
);

// Función para inicializar un nuevo cliente de WhatsApp con depuración detallada
function initWhatsAppClient(sessionId: string, isNewSession: boolean): Client {
  console.log(
    `Comenzando la inicialización del cliente de WhatsApp para la sesión ID: ${sessionId}`
  );

  // Solo borrar datos de sesión antiguos si es una nueva sesión
  const sessionPath = path.join(SESSIONS_DIR, sessionId);
  if (isNewSession && fs.existsSync(sessionPath)) {
    console.log(`Borrando datos de sesión antiguos para ID: ${sessionId}`);
    try {
      fs.rmSync(sessionPath, { recursive: true });
      console.log(`Datos de sesión antiguos borrados para ID: ${sessionId}`);
    } catch (error) {
      handleServerError(
        error,
        `Error al borrar datos de sesión antiguos para ID: ${sessionId}`
      );
      registrarError(error, sessionId);
    }
  }

 // Eliminar webVersionCache para forzar descarga de la última versión de WhatsApp Web
  const webVersionCachePath = path.join(sessionPath, '.wwebjs_auth', 'webVersionCache.json');
  if (!isNewSession && fs.existsSync(webVersionCachePath)) {
    try {
      fs.unlinkSync(webVersionCachePath);
      console.log(`🗑️ webVersionCache eliminado para sesión ${sessionId} - forzará descarga de última versión WA Web`);
    } catch (error) {
      console.log(`⚠️ No se pudo eliminar webVersionCache para sesión ${sessionId}:`, error);
    }
  }

// Configura el cliente de WhatsApp con opciones específicas
  const client = new Client({
    authStrategy: new LocalAuth({
      clientId: sessionId,
      dataPath: path.join(SESSIONS_DIR, sessionId), // Asegúrate de que cada sesión tiene su propia carpeta
    }),
    puppeteer: {
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-dev-shm-usage",
        "--disable-accelerated-2d-canvas",
        "--no-first-run",
        "--disable-extensions",
        "--disable-gpu",
      ],
      headless: true, // Modo headless DESACTIVADO para debug
      // Usar Google Chrome del sistema en Docker, Chromium de puppeteer en local
      executablePath: process.env.DOCKER_ENV === 'true'
        ? '/usr/bin/google-chrome-stable'
        : undefined,
    },
    // Sin version pinning - usa la versión más reciente disponible

    takeoverOnConflict: true,
  });

After that, it only uses client.on events

uncut swan
#

Hello, any news on that ? Having the same problem

fervent moss
#

me too

tacit breach
#

hello is there update for this issue, im facing same problem

glacial wraith
#

me too

jaunty wyvern
#

I'm having the same problem, the strangest thing is that I have about 10 instances. Some instances connect and start working normally again. Others don't. I also noticed that it's always the same WhatsApp numbers that stop connecting. Of the 10, 8 connect and 2 don't show the ready event.

hard vale
tacit breach
knotty badger
native holly
tacit breach
#

does anyone know how to pair with code?

native holly