Deploy a Telegram bot on NodeJS to a VPS with grammY and PM2

· 0x.cloud Team

Deploy a Telegram bot on NodeJS to a VPS with grammY and PM2

To deploy a Telegram bot on NodeJS, install Node.js 26 LTS on an Ubuntu 24.04 server, pull your code, put the bot token in a .env file, and run the bot under PM2 with pm2 startup and pm2 save. PM2 restarts the bot when it crashes and brings it back after a reboot. Long polling needs no domain at all; for a webhook, add Nginx and a free Let's Encrypt certificate. Versions checked on Nov 20, 2026: Node.js 26.13 LTS, grammY 1.46, PM2 7.1.

Hand the whole job to your AI agent. Paste this into Claude Code, Cursor or ChatGPT with the 0x.cloud MCP server connected:

Prompt for an AI agent

Create an s1-1 server with Ubuntu 24.04 on 0x.cloud. Show me the dry_run price first and wait for my "yes". Then, with run_command, create a sudo user named bot, install Node.js 26 LTS from NodeSource and PM2, clone my repo <URL>, run npm ci --omit=dev, write the token I give you into .env with mode 600, start the bot with a PM2 ecosystem file, run pm2 startup and pm2 save, and send me the pm2 status output.

The agent's key needs servers.read, servers.create (dry_run requires it too) and servers.exec. New keys default to servers.*, which includes deleting servers, so remove that scope in the dashboard if the agent doesn't need it.

What you need and which plan to pick

Simple bot Bot with an LLM or a database
Server 1 vCPU, 1 GB RAM, 15 GB NVMe (s1-1, $4.49/mo) 1 vCPU, 2 GB RAM, 30 GB NVMe (s1-2, $7.99/mo)
OS Ubuntu 24.04 LTS or Debian 12 same
Token from @BotFather same
Domain not needed for polling needed for a webhook

Our pick: s1-1 at $4.49/mo, about $0.030750 an hour. A polling grammY bot sits at 60–150 MB of RAM and barely touches the CPU while it waits for messages, so 1 GB fits 3–5 bots, each as its own PM2 process.

Go with s1-2 if the bot calls LLM APIs, keeps SQLite or resizes images. The server is in Warsaw, setup is $0, and on hourly billing you can delete it after a test and get the unused balance back. Plans tuned for bots are listed on Telegram bot hosting.

Prepare the server

Open the web console of the server in your cabinet (an agent runs the same commands with run_command), update packages and turn on the firewall. A polling bot makes only outgoing connections, so SSH is the only port you open:

sudo apt update && sudo apt upgrade -y
sudo ufw allow OpenSSH
sudo ufw enable

Don't run the bot as root. Create a dedicated user (details in add a sudo user on Ubuntu) and switch to it:

sudo adduser bot
sudo usermod -aG sudo bot
su - bot

Install Node.js 26 LTS from NodeSource, plus Git and PM2:

curl -fsSL https://deb.nodesource.com/setup_26.x -o nodesource_setup.sh
sudo -E bash nodesource_setup.sh
sudo apt install -y nodejs git
sudo npm install -g pm2
node -v && pm2 -v

The NodeSource script adds the Node.js 26 repository, the current LTS line. Ubuntu's own nodejs package is several major versions behind, so skip it. On the 0x.cloud bots image, Node.js and PM2 come preinstalled and you can skip this step. Check node -v first: the --env-file flag used below needs Node.js 20.6 or newer.

Which Node.js Telegram bot library to use

Library Latest release (as of Nov 20, 2026) Pick it when
grammY 1.46.0, August 2026 starting a new bot: TypeScript types, plugins, detailed hosting docs
Telegraf 4.16.3, February 2024 you already have a Telegraf bot: deployment is identical, but releases are rare
node-telegram-bot-api 2.4.0, November 2026 a simple bot without middleware, or an older project

This guide uses grammY, but the server, PM2 and webhook steps are the same for all three.

Write or clone the bot

If your bot lives in Git, clone it into ~/tg-bot and jump to the .env step. To test the pipeline, here is a minimal grammY bot:

mkdir ~/tg-bot && cd ~/tg-bot
npm init -y
npm pkg set type=module
npm install grammy
nano bot.js
import { Bot } from "grammy";

const bot = new Bot(process.env.BOT_TOKEN);

bot.command("start", (ctx) => ctx.reply("Running on a VPS, 24/7."));
bot.on("message:text", (ctx) => ctx.reply(`You said: ${ctx.message.text}`));

bot.catch((err) => console.error("Handler error:", err.error));
bot.start();

bot.start() uses long polling: the bot asks Telegram for updates, so nothing on the server has to accept inbound traffic. bot.catch keeps one bad update from killing the process.

Keep the token out of your code:

echo "BOT_TOKEN=123456:ABC-your-token" > .env
chmod 600 .env
echo ".env" >> .gitignore

For API keys of LLM providers and other secrets, see how to store API keys on a server.

Run it once by hand with node --env-file=.env bot.js. The --env-file flag is built into Node.js, so you don't need dotenv. Send /start, get the reply, then press Ctrl+C.

Using Telegraf? Replace bot.start() with bot.launch() and follow the rest of this guide unchanged. A Python version with aiogram is in deploy a Python Telegram bot.

Deploy the Telegram bot on NodeJS under PM2

Create ecosystem.config.cjs next to bot.js:

module.exports = {
  apps: [{
    name: "tg-bot",
    script: "bot.js",
    node_args: "--env-file=.env",
    max_memory_restart: "300M",
    restart_delay: 3000,
  }],
};
  • node_args loads the token from .env into the process;
  • max_memory_restart restarts the bot if a leak pushes it past 300 MB;
  • restart_delay waits 3 seconds between restarts so a crash loop doesn't hammer the Bot API.

Start it and register PM2 with systemd:

pm2 start ecosystem.config.cjs
pm2 startup

pm2 startup prints a command that begins with sudo env PATH=…. Copy it and run it. PM2 creates a pm2-bot systemd service. Then save the process list so it's restored on boot:

pm2 save
pm2 status
pm2 logs tg-bot --lines 50

Test with sudo reboot. Logs go to ~/.pm2/logs; add rotation with pm2 install pm2-logrotate so they don't fill the disk. Cluster mode and zero-downtime reloads are covered in deploy Node.js with PM2.

Switch to a webhook with a domain and HTTPS

Telegram delivers webhooks only over HTTPS on ports 443, 80, 88 or 8443. Incoming connections from the internet don't reach 0x.cloud servers, so keep long polling there; the steps below are for a server with a public address. Point an A record for bot.example.com at the server IP, then:

sudo ufw allow 'Nginx Full'
sudo apt install -y nginx
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

In bot.js, replace bot.start() with a local HTTP server. It listens on 127.0.0.1 only, so the outside world reaches it through Nginx:

import { createServer } from "node:http";
import { webhookCallback } from "grammy";

const handle = webhookCallback(bot, "http", { secretToken: process.env.WEBHOOK_SECRET });
createServer(handle).listen(3000, "127.0.0.1");

Add WEBHOOK_SECRET= to .env with a value from openssl rand -hex 32. Telegram sends it in a header with every update, and grammY rejects requests without it.

Create /etc/nginx/sites-available/tg-bot:

server {
    listen 80;
    server_name bot.example.com;

    location /tg-webhook {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
sudo ln -s /etc/nginx/sites-available/tg-bot /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d bot.example.com
pm2 restart tg-bot

Certbot issues the certificate, switches the site to HTTPS and schedules renewal. Register the webhook with Telegram:

curl "https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://bot.example.com/tg-webhook&secret_token=<SECRET>"

getWebhookInfo shows the current URL and last_error_message if deliveries fail.

Update the bot

cd ~/tg-bot
git pull
npm ci --omit=dev
pm2 restart tg-bot

npm ci installs exactly what package-lock.json lists, and --omit=dev skips dev dependencies. To bump grammY, run npm install grammy@latest locally, test, and commit the lock file. After a major Node.js upgrade, run pm2 unstartup, pm2 startup and pm2 save again.

Back up the bot

Your code is in Git. What you can't recreate is the token file and any local data:

tar czf ~/tg-bot-$(date +%F).tar.gz -C ~ tg-bot/.env tg-bot/ecosystem.config.cjs

If the bot keeps SQLite or uploads in a folder such as tg-bot/data, append it to the command, and copy the archive off the server, for example with scp to another machine of yours. On 0x.cloud you can also turn on automatic backups (7 daily copies, +20% of the plan price) or take a $0.99/mo snapshot before a risky change.

Common errors

Symptom Cause and fix
409 Conflict: terminated by other getUpdates request Two copies are polling, for example your laptop and the server. Stop one
409 Conflict: can't use getUpdates while webhook is active A webhook is still set. Call deleteWebhook or run in webhook mode
401 Unauthorized Wrong token or .env not loaded. Check node_args in the ecosystem file
Cannot use import statement outside a module "type": "module" is missing from package.json
Bot is gone after a reboot You skipped the command printed by pm2 startup or pm2 save
wrong response from the webhook: 502 Nothing listens on 127.0.0.1:3000. Check pm2 logs tg-bot

Official reference: grammY hosting guide for a VPS.

FAQ

How much server do I need for a Node.js Telegram bot? A typical grammY bot uses 60–150 MB of RAM, so 1 vCPU and 1 GB (the s1-1 plan, $4.49/mo) is enough. Pick s1-2 with 2 GB if the bot calls LLM APIs, keeps a database or processes images.

Should I use long polling or a webhook? Start with long polling: no domain, no certificate, no open ports. Switch to a webhook when traffic grows or you want lower latency. It needs a domain with HTTPS on port 443, 80, 88 or 8443.

Why does my bot stop when I close the SSH session? A process started with node bot.js belongs to your SSH session and dies with it. Run the bot under PM2 or a systemd service so it keeps running in the background and restarts after crashes and reboots.

What if the server isn't right or I break something? Use hourly billing: s1-1 costs about $0.030750 an hour, so a day costs about $0.74. Delete the server and charges stop at once, with the unused balance returned. Reinstalling the OS is $0, and a snapshot before a risky change is $0.99/mo.

Does this guide work for a Telegraf bot? Yes. The only difference is the start call: Telegraf uses bot.launch() instead of bot.start(). Node.js, PM2, boot persistence, updates and the Nginx webhook setup are the same. Note that Telegraf's latest release (4.16.3) shipped in February 2024, so grammY is the safer pick for a new bot.

Deploy to 0x.cloud