> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Host a WhatsApp Bot 24/7

> Host a WhatsApp bot 24/7 on Square Cloud with whatsapp-web.js or Baileys: scan the QR Code from the logs, keep the session saved and deploy.

export const RecommendedPlan = ({lang, plan, tier, cpu, appType, min}) => {
  const t = {
    'en': {
      q: <>Which plan should you choose for {appType}?</>,
      rec: p => <>We recommend the {p} plan: its <b>{tier} GB</b> of RAM and <b>{cpu} vCPU</b> handle most projects of this kind, with headroom for traffic spikes.</>,
      min: m => <> Lighter projects also run on the {m} plan.</>,
      pro: p => <> For larger projects, the {p} plan adds more RAM and CPU.</>
    },
    'pt-br': {
      q: <>Qual plano escolher para {appType}?</>,
      rec: p => <>Recomendamos o plano {p}: seus <b>{tier} GB</b> de RAM e <b>{cpu} vCPU</b> atendem a maioria dos projetos desse tipo, com folga para picos de tráfego.</>,
      min: m => <> Projetos mais leves também rodam no plano {m}.</>,
      pro: p => <> Para projetos maiores, o plano {p} oferece mais RAM e CPU.</>
    },
    'es': {
      q: <>¿Qué plan elegir para {appType}?</>,
      rec: p => <>Te recomendamos el plan {p}: sus <b>{tier} GB</b> de RAM y <b>{cpu} vCPU</b> cubren la mayoría de los proyectos de este tipo, con margen para picos de tráfico.</>,
      min: m => <> Los proyectos más ligeros también funcionan en el plan {m}.</>,
      pro: p => <> Para proyectos más grandes, el plan {p} ofrece más RAM y CPU.</>
    },
    'fr': {
      q: <>Quel plan choisir pour héberger {appType} ?</>,
      rec: p => <>Nous recommandons le plan {p} : ses <b>{tier} Go</b> de RAM et <b>{cpu} vCPU</b> suffisent pour la plupart des projets de ce type, avec une marge pour les pics de trafic.</>,
      min: m => <> Les projets plus légers fonctionnent aussi avec le plan {m}.</>,
      pro: p => <> Pour les projets plus importants, le plan {p} offre davantage de RAM et de CPU.</>
    },
    'de': {
      q: <>Welcher Plan eignet sich für {appType}?</>,
      rec: p => <>Wir empfehlen den {p}-Plan: <b>{tier} GB</b> RAM und <b>{cpu} vCPU</b> reichen für die meisten Projekte dieser Art, mit Reserven für Lastspitzen.</>,
      min: m => <> Kleinere Projekte laufen auch mit dem {m}-Plan.</>,
      pro: p => <> Für größere Projekte bietet der {p}-Plan mehr RAM und CPU.</>
    },
    'it': {
      q: <>Quale piano scegliere per {appType}?</>,
      rec: p => <>Ti consigliamo il piano {p}: i suoi <b>{tier}GB</b> di RAM e <b>{cpu}vCPU</b> bastano per la maggior parte dei progetti di questo tipo, con margine per i picchi di traffico.</>,
      min: m => <> I progetti più leggeri funzionano anche con il piano {m}.</>,
      pro: p => <> Per progetti più grandi, il piano {p} offre più RAM e CPU.</>
    },
    'ja': {
      q: <>{appType}にはどのプランを選べばよいですか？</>,
      rec: p => <>{p}プランをおすすめします。<b>{tier}GB</b>のRAMと<b>{cpu}vCPU</b>があれば、この種のプロジェクトの多くをトラフィックのピークにも余裕を持って動かせます。</>,
      min: m => <>軽量なプロジェクトは{m}プランでも動作します。</>,
      pro: p => <>より大規模なプロジェクトには、RAMとCPUが増える{p}プランをご検討ください。</>
    },
    'zh': {
      q: <>托管{appType}应该选择哪个套餐？</>,
      rec: p => <>我们推荐 {p} 套餐：<b>{tier}GB</b> RAM 和 <b>{cpu}vCPU</b> 足以运行大多数此类项目，并能从容应对流量高峰。</>,
      min: m => <>较轻量的项目也可以在 {m} 套餐上运行。</>,
      pro: p => <>对于更大的项目，{p} 套餐提供更多 RAM 和 CPU。</>
    }
  };
  const siteLang = t[lang] ? lang : 'en';
  const c = t[siteLang];
  const pay = (name, query) => <a href={`https://squarecloud.app/${siteLang}/pay?${query}`}>{name}</a>;
  const isPro = plan.toLowerCase() === 'pro';
  return <Note>
      <b>{c.q}</b><br />
      {c.rec(pay(plan, `plan=${plan.toLowerCase()}&tier=${tier}`))}
      {min ? c.min(pay(min, `plan=${min.toLowerCase()}`)) : null}
      {isPro ? null : c.pro(pay('Pro', 'plan=pro'))}
    </Note>;
};

export const appType_0 = "a WhatsApp bot"

## Introduction

To develop and host {appType_0} on Square Cloud, it's essential to follow a structured sequence of configurations and prerequisites. This technical guide will cover the entire process, from initial setup to production deployment.

### Prerequisites

* **Square Cloud Account**: Register through the [signup page](https://squarecloud.app/en/signup) using your email.
* **Active plan**: Ensures dedicated resources and optimized performance for your application. Check our [available plans](https://squarecloud.app/en/pricing) and choose the most suitable for your needs.

<RecommendedPlan appType="WhatsApp bots" plan="Standard" tier="4" cpu="4" min="Hobby" lang="en" />

This guide runs on the [Node.js runtime](/en/articles/getting-started-with-nodejs).

## Create the project

You need WhatsApp installed on your phone to link the bot to your account. If you don't have the app, visit the [official WhatsApp website](https://www.whatsapp.com/download) for download and setup.

1. **Node.js verification**: Confirm that Node.js is installed on your system. Otherwise, download it from the [official Node.js website](https://nodejs.org/).

2. **Project initialization**: Set up a new Node.js project by running the initialization command:

```bash Terminal theme={"system"}
npm init -y
```

3. **Dependencies installation**: Install the essential libraries for bot functionality:

```bash Terminal theme={"system"}
npm install whatsapp-web.js qrcode-terminal
```

## Develop the bot

Create the `index.js` file with the bot's base structure:

```javascript index.js theme={"system"}
// Import necessary modules
const { Client, LocalAuth } = require("whatsapp-web.js");
const qrcode = require("qrcode-terminal");

// Create a new WhatsApp client instance
const client = new Client({
  // Save the session in the .wwebjs_auth folder, so restarts don't ask for a new QR Code
  authStrategy: new LocalAuth(),
  puppeteer: {
    // Run Chrome in headless mode (without graphical interface)
    headless: true,
    args: [
      // Disable Chrome sandboxing features
      // Required for execution in containerized environments
      "--no-sandbox",
      // Additional sandboxing flag to disable setuid sandbox
      "--disable-setuid-sandbox",
    ],
  },
});

// Event listener for QR Code generation
client.on("qr", (qr) => {
  // Print the QR Code in the logs, so you can scan it from the Square Cloud dashboard
  qrcode.generate(qr, { small: true });
  console.log("Scan the QR Code above in WhatsApp: Linked devices > Link a device");
});

// Event listener for client ready
client.on("ready", () => {
  // Confirmation log when WhatsApp Web session is established
  console.log("WhatsApp client successfully initialized!");
});

// Event listener for created messages
client.on("message_create", (msg) => {
  // Log message content to console
  console.log("Message received:", msg.body);
  
  // Test command implementation
  if (msg.body === "!ping") {
    // Automatic response for ping command
    msg.reply("pong - Bot working correctly!");
  }
});

// Initialize WhatsApp client
client.initialize();
```

## Configure Square Cloud

Create a `squarecloud.app` file at the root of your project, next to `index.js`. It tells Square Cloud how to run your bot:

```systemd squarecloud.app theme={"system"}
DISPLAY_NAME=My WhatsApp Bot
MAIN=index.js
MEMORY=1024
VERSION=recommended
AUTORESTART=true
```

* `MEMORY` is the bot's RAM in MB. whatsapp-web.js runs a headless Chromium browser, so give it at least 1024 MB.
* `AUTORESTART=true` starts the bot again if it crashes. See [how auto restart works](https://help.squarecloud.app/en-us/article/how-to-use-auto-restart-on-square-cloud-nmhvh0/).
* There is no `SUBDOMAIN`: the bot doesn't serve web pages.

See the [configuration file reference](/en/getting-started/config-file) for every field.

## What goes in the ZIP

* `index.js` and your other source files.
* `package.json`.
* `squarecloud.app`.

Leave out `node_modules`: Square Cloud installs your dependencies when the bot starts. Also leave out the `.wwebjs_auth` and `.wwebjs_cache` folders that a run on your computer creates, so the bot links its own session on Square Cloud. If you upload with the CLI, list both folders in your [`squarecloud.ignore`](/en/getting-started/squarecloud-ignore) file.

## Deploy and verify

Create the ZIP described above, then upload it:

### Via dashboard

<Steps>
  <Step title="Access the Upload Page">
    Access the [upload page](https://squarecloud.app/en/dashboard/new) and upload your project zip file.
  </Step>

  <Step title="Configure Your Environment">
    After uploading your zip, you will need to configure the name, main file or runtime environment and other settings for your project.\
    If you are uploading a web project, make sure to select "Web Publication" and set a subdomain to your project.
  </Step>

  <Step title="Deploy Your Project">
    Finally, click on the "Deploy" button to host your project on Square Cloud.\
    After deployment, you can monitor your project's status and logs from the dashboard.

    <Frame>
      <img src="https://cdn.squarecloud.app/docs/articles/dashboard/uploading.gif" alt="Uploading application to Square Cloud" style={{ borderRadius: "0.2rem" }} />
    </Frame>
  </Step>

  <Step title="Confirm Your App Is Live">
    Your first deploy usually takes less than a minute. In the [dashboard](https://squarecloud.app/en/dashboard), wait for your application status to show as running and check the logs for any startup errors.\
    If you deployed a website or API, open `https://<your-subdomain>.squareweb.app` in your browser: you should see your application responding. If you deployed a bot, send it a command to confirm it is online.
    <Tip>App not starting? See the [Troubleshooting guide](/en/platform/troubleshooting/app-wont-start) for the most common causes and fixes.</Tip>
  </Step>
</Steps>

### Via CLI

To use this method, your project needs a configuration file named `squarecloud.app` at its root. It tells Square Cloud how to run your application.

<Card title="Configuration file guide" icon="link" href="/en/getting-started/config-file">
  Learn how to create the `squarecloud.app` configuration file that defines your application's environment.
</Card>

<Steps>
  <Step title="Install the CLI">
    Install the [Square Cloud CLI](/en/cli-reference/installation). If you already have it, run the same command to update it:

    <CodeGroup>
      ```bash macOS, Linux, and WSL theme={"system"}
      curl -fsSL https://cli.squarecloud.app/install | bash
      ```

      ```bash Windows with npm theme={"system"}
      npm install -g @squarecloud/cli@latest
      ```
    </CodeGroup>
  </Step>

  <Step title="Log In">
    Run the command below. It opens your browser: approve the login there and the CLI is ready. There is no API key to copy. For scripts and CI, see [CLI authentication](/en/cli-reference/authentication).

    ```bash theme={"system"}
    squarecloud auth login
    ```
  </Step>

  <Step title="Upload Your Project">
    From your project folder, run the command below. The CLI zips the current folder, leaving out what [`squarecloud.ignore`](/en/getting-started/squarecloud-ignore) lists, and uploads it:

    ```bash theme={"system"}
    squarecloud upload
    ```

    To upload a zip you created yourself, pass it with `--file`:

    ```bash theme={"system"}
    squarecloud upload --file <path/to/zip>
    ```
  </Step>

  <Step title="Confirm Your App Is Live">
    Your first deploy usually takes less than a minute. Check your application status and logs directly from the terminal:

    ```bash theme={"system"}
    squarecloud app status
    squarecloud app logs
    ```

    If you deployed a website or API, open `https://<your-subdomain>.squareweb.app` in your browser: you should see your application responding. If you deployed a bot, send it a command to confirm it is online.
    <Tip>App not starting? See the [Troubleshooting guide](/en/platform/troubleshooting/app-wont-start) for the most common causes and fixes.</Tip>
  </Step>
</Steps>

### Link your WhatsApp account

Open the application logs in the Square Cloud dashboard. On first boot, the bot prints a QR Code there: on your phone, open WhatsApp, go to **Linked devices** > **Link a device** and scan it. The `WhatsApp client successfully initialized!` message confirms the session is active. Then send `!ping` from another number to the linked WhatsApp account and confirm it replies with `pong - Bot working correctly!`.

`LocalAuth` saves the session in the `.wwebjs_auth` folder, so restarts reconnect without a new QR Code. To link a different number, delete that folder and restart the application.

## Common errors

### The QR Code can't be scanned

The QR Code is drawn with text characters, and WhatsApp replaces it periodically, so scan the most recent one. If your phone can't read it, zoom out until the whole code fits on screen, or switch the dashboard to the dark theme.

### Login stopped working after a WhatsApp Web update

Update the library with `npm install whatsapp-web.js@latest` and deploy again. Avoid pinning an old WhatsApp Web version with the `webVersionCache` option: outdated versions tend to break login.

### The bot runs out of memory

whatsapp-web.js runs a headless Chromium browser, which needs memory. Keep `MEMORY` at 1024 MB or more, or switch to [Baileys](#use-baileys-instead-of-whatsapp-webjs), which runs without a browser.

## Use Baileys instead of whatsapp-web.js

[Baileys](https://github.com/WhiskeySockets/Baileys) is an alternative library that connects to WhatsApp's multi-device API directly over a WebSocket, without launching a headless browser. Since there's no Chromium/Puppeteer instance to run, it uses significantly less RAM than whatsapp-web.js.

Baileys saves its session (the `creds.json` file and keys) in the `auth` folder through `useMultiFileAuthState`. Square Cloud keeps your application's files between restarts, so you only need to scan the QR Code again if you log out or delete that folder. As with `.wwebjs_auth`, leave a local `auth` folder out of your ZIP.

1. Install the library:

```bash Terminal theme={"system"}
npm install @whiskeysockets/baileys qrcode-terminal
```

2. Create an `index.js` file using `makeWASocket` and `useMultiFileAuthState` to load and persist the session:

```javascript index.js theme={"system"}
const { makeWASocket, useMultiFileAuthState } = require("@whiskeysockets/baileys");
const qrcode = require("qrcode-terminal");

async function startBot() {
  // Load (or create) the authentication state from the "auth" folder.
  // Square Cloud keeps this folder between restarts, so the session survives.
  const { state, saveCreds } = await useMultiFileAuthState("auth");

  const sock = makeWASocket({
    auth: state,
  });

  // Persist updated credentials whenever Baileys rotates them
  sock.ev.on("creds.update", saveCreds);

  // Print the QR Code on first login and reconnect when the socket closes
  sock.ev.on("connection.update", ({ connection, qr, lastDisconnect }) => {
    if (qr) {
      // Print the QR Code in the logs, so you can scan it from the Square Cloud dashboard
      qrcode.generate(qr, { small: true });
      console.log("Scan the QR Code above in WhatsApp: Linked devices > Link a device");
    }
    if (connection === "close") {
      const loggedOut = lastDisconnect?.error?.output?.statusCode === 401;
      if (!loggedOut) startBot();
    }
  });

  // Reply to a basic command
  sock.ev.on("messages.upsert", async ({ messages }) => {
    const msg = messages[0];
    if (!msg.message || msg.key.fromMe) return;

    if (msg.message.conversation === "!ping") {
      await sock.sendMessage(msg.key.remoteJid, { text: "pong - Bot working correctly!" });
    }
  });
}

startBot();
```

Since Baileys doesn't need a browser, its configuration file on Square Cloud can use a lower `MEMORY` value than the whatsapp-web.js example above:

```systemd squarecloud.app theme={"system"}
DISPLAY_NAME=My WhatsApp Bot
MAIN=index.js
MEMORY=512
VERSION=recommended
AUTORESTART=true
```

## Next steps

<CardGroup cols={3}>
  <Card title="App won't start" icon="triangle-exclamation" href="/en/platform/troubleshooting/app-wont-start">
    Fix missing modules, memory errors and other startup failures.
  </Card>

  <Card title="Evolution API" icon="comment" href="/en/tutorials/how-to-deploy-evolution-api">
    Run a WhatsApp API that manages many instances at once.
  </Card>

  <Card title="Bot hosting" icon="robot" href="/en/services/bots">
    What Square Cloud offers for bots that run 24/7.
  </Card>
</CardGroup>

For more about whatsapp-web.js, see the [official whatsapp-web.js documentation](https://wwebjs.dev/).

## Contact us

If you continue facing **technical difficulties**, our **specialized support team** is available to assist you. [**Contact us**](https://squarecloud.app/en/support) and we'll be happy to help you resolve any issue: support quality is a big part of why developers rate Square Cloud [**4.9/5 across 402 reviews**](https://www.trustpilot.com/review/squarecloud.app) on Google and Trustpilot.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.