# Build your first Telegram bot in Node.js with fetch

> A Telegram bot in Node.js with built-in fetch, no library: getMe, getUpdates long polling, sendMessage with HTML escaping, a clean stop and setWebhook.

Published 2026-11-04. Z-API Omni team.

A Telegram bot in Node.js needs no npm package. Node's built-in `fetch` calls the Bot API directly: `getMe` tests the token, `getUpdates` long-polls for messages and `sendMessage` replies. The script below runs on Node.js 26 LTS, also 22 and 24 ([Node.js releases](https://nodejs.org/en/about/previous-releases), accessed 2026-11-04). It follows Bot API 10.3 (August 24, 2026) and stops cleanly on Ctrl+C. Telegram publishes no request samples for these methods, so every payload here is assembled from the parameter tables in the [Bot API reference](https://core.telegram.org/bots/api) (accessed 2026-11-04). The [Python version of this bot](/academy/articles/telegram-bot-send-message-python-getting-started/) covers the token, the offset rules and the 24-hour update retention.

## What Node.js gives you without packages

Node's `fetch` has been stable since v21.0.0, when its history entry reads "No longer experimental" ([Node.js globals](https://nodejs.org/api/globals.html), accessed 2026-11-04). `AbortSignal.timeout()` puts a deadline on a request, and `AbortSignal.any()`, added in v20.3.0, combines that deadline with a stop signal of your own. The `--env-file` flag loads a `.env` file into `process.env`. It stopped being experimental in v24.10.0 and v22.21.0 ([Node.js CLI](https://nodejs.org/api/cli.html), accessed 2026-11-04).

## One function for every Bot API call

Every method is an HTTPS request to `https://api.telegram.org/bot<token>/METHOD_NAME`, and a JSON body works for everything except file uploads ([Making requests](https://core.telegram.org/bots/api#making-requests)). The response always carries a Boolean `ok`. On success the data is in `result`, and on failure `description` explains the error. Telegram says the integer `error_code` is "subject to change in the future", so the code branches on `ok`.

Node's `fetch` doesn't throw on a 4xx or 5xx status, unlike Python's urllib. The `call` function reads the JSON body and checks `ok` itself. `fetch` does throw on network failures and aborts, and the loop catches those. A proxy or an outage page can also answer with HTML, so a body that isn't JSON becomes a normal error instead of a `SyntaxError`.

Flood-control errors carry `parameters.retry_after`, "the number of seconds left to wait before the request can be repeated" ([ResponseParameters](https://core.telegram.org/bots/api#responseparameters)). The `TelegramError` class keeps that value, and the polling loop waits that long before trying again.

## Long polling with offset and a client timeout

`getUpdates` with a positive `timeout` holds the request open until an update arrives or the time runs out. The default of 0 is short polling, which "should be used for testing purposes only" ([getUpdates](https://core.telegram.org/bots/api#getupdates)). Pass `offset` as the last `update_id` plus one. On the first call `offset` is `undefined`, which `JSON.stringify` drops, so Telegram returns the earliest unconfirmed updates. The [parameter table in the Python post](/academy/articles/telegram-bot-send-message-python-getting-started/) covers `limit` and `allowed_updates`.

Telegram doesn't document how long your HTTP client should wait. The script asks Telegram to hold the poll for 30 seconds and aborts the fetch after 40. That 10-second margin is our choice. Set the client deadline at or below 30 and every quiet period ends in an abort error instead of an empty array.

## The complete bot

Create a `.env` file with one line, `TELEGRAM_BOT_TOKEN=YOUR_TOKEN`, and save the script as `bot.mjs`. The `.mjs` extension makes it an ES module, so top-level `await` works.

```javascript
// bot.mjs. Run: node --env-file=.env bot.mjs
const TOKEN = process.env.TELEGRAM_BOT_TOKEN;
if (!TOKEN) throw new Error('TELEGRAM_BOT_TOKEN is not set');
const API = `https://api.telegram.org/bot${TOKEN}/`;
const POLL_SECONDS = 30; // how long Telegram holds getUpdates open

const stop = new AbortController();
for (const name of ['SIGINT', 'SIGTERM']) {
  process.once(name, () => {
    console.log(`${name} received, stopping`);
    stop.abort();
  });
}

class TelegramError extends Error {
  constructor(method, body) {
    super(`${method}: ${body.description}`);
    this.retryAfter = body.parameters?.retry_after;
  }
}

async function call(method, params = {}, { timeoutMs = 10_000, signal } = {}) {
  const deadline = AbortSignal.timeout(timeoutMs);
  const res = await fetch(API + method, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
    signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
  });
  const body = await res.json().catch(() => ({ ok: false, description: `HTTP ${res.status}, body is not JSON` }));
  if (!body.ok) throw new TelegramError(method, body);
  return body.result;
}

function sleep(ms) {
  return new Promise((resolve) => {
    if (stop.signal.aborted) return resolve();
    const timer = setTimeout(resolve, ms);
    stop.signal.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
  });
}

const escapeHtml = (s) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');

async function handle(message) {
  if (typeof message.text !== 'string') return; // photos, stickers and other non-text messages
  await call('sendMessage', {
    chat_id: message.chat.id,
    text: `You said: <b>${escapeHtml(message.text.slice(0, 4000))}</b>`,
    parse_mode: 'HTML',
    reply_parameters: { message_id: message.message_id },
    link_preview_options: { is_disabled: true },
  });
}

const me = await call('getMe');
console.log(`Running as @${me.username} (id ${me.id})`);

if ((await call('getWebhookInfo')).url) {
  console.error('A webhook is set. Call deleteWebhook before polling.');
  process.exit(1);
}

let offset;
while (!stop.signal.aborted) {
  let updates;
  try {
    updates = await call(
      'getUpdates',
      { offset, timeout: POLL_SECONDS, allowed_updates: ['message'] },
      { timeoutMs: (POLL_SECONDS + 10) * 1000, signal: stop.signal },
    );
  } catch (err) {
    if (stop.signal.aborted) break;
    console.error('getUpdates failed:', err.message);
    await sleep((err.retryAfter ?? 5) * 1000);
    continue;
  }
  for (const update of updates) {
    offset = update.update_id + 1;
    if (!update.message) continue;
    try {
      await handle(update.message);
    } catch (err) {
      console.error(`update ${update.update_id} failed:`, err.message);
    }
  }
}

// Confirm the last batch so it isn't delivered again on the next start.
if (offset !== undefined) {
  await call('getUpdates', { offset, timeout: 0, limit: 1 })
    .catch((err) => console.error('final confirm failed:', err.message));
}
console.log('Stopped');
```

Run it with `node --env-file=.env bot.mjs` and message the bot from your Telegram account. It answers as a reply to your message, with your text in bold. `link_preview_options.is_disabled` keeps a pasted URL from expanding into a preview card. The slice to 4,000 characters keeps the reply under the 4,096-character limit of `text` once the prefix is added ([sendMessage](https://core.telegram.org/bots/api#sendmessage)).

## Escaping text for HTML and MarkdownV2

The reply uses HTML mode. Every `<`, `>` and `&` that isn't part of a tag or an entity must be replaced with `&lt;`, `&gt;` and `&amp;` ([Formatting options](https://core.telegram.org/bots/api#formatting-options)). `escapeHtml` replaces `&` first. Done last, it would turn the `&lt;` written a moment earlier into `&amp;lt;`.

In MarkdownV2, outside entities, 18 characters must be escaped with a backslash, and the backslash itself must be escaped too. Inside `pre` and `code`, only the backtick and the backslash need it. The function below handles text outside entities. The regex is ours, built from Telegram's list.

```javascript
const escapeMarkdownV2 = (s) => s.replace(/[_*\[\]()~`>#+\-=|{}.!\\]/g, '\\$&');
```

Ordinary sentences contain `.`, `-` and `!`, so unescaped user text breaks MarkdownV2 on any message with a period. Telegram calls plain `Markdown` "a legacy mode, retained for backward compatibility". Use HTML for user input and MarkdownV2 only for text you write yourself.

## Stopping cleanly on Ctrl+C

Node's default handlers for SIGINT and SIGTERM exit at once on non-Windows platforms, with code `128 + signal number`. "If one of these signals has a listener installed, its default behavior will be removed" ([process signal events](https://nodejs.org/api/process.html), accessed 2026-11-04). The bot's listeners abort the `stop` controller instead. The pending `getUpdates` fetch rejects, the loop ends after the batch it's working on, and no reply is cut off halfway.

Before exiting, the bot calls `getUpdates` once more with the new `offset` and `timeout: 0`. Telegram treats an update as confirmed "as soon as getUpdates is called with an offset higher than its update_id" ([getUpdates](https://core.telegram.org/bots/api#getupdates)). Skip that closing call and the last batch is still unconfirmed, so it arrives again on the next start and users get a second reply. Telegram doesn't say if an abort cancels the poll on its side. The closing call works either way.

The listeners use `process.once`. After the first signal no listener is left, so a second Ctrl+C gets Node's default exit and ends a shutdown that hangs. On Windows, SIGTERM "is not supported", while SIGINT from Ctrl+C "is supported on all platforms". Stop the bot with Ctrl+C there. On Linux and macOS, `kill` sends SIGTERM and takes the same path.

## Switching to setWebhook

On a server with an HTTPS domain, `setWebhook` replaces the polling loop. Telegram then sends "an HTTPS POST request to the specified URL" with one Update in the body. A response outside `2XY` gets repeated, and Telegram gives up "after a reasonable amount of attempts" ([setWebhook](https://core.telegram.org/bots/api#setwebhook)).

```bash
curl -X POST "https://api.telegram.org/botYOUR_TOKEN/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://YOUR_DOMAIN/telegram","secret_token":"YOUR_SECRET","allowed_updates":["message"]}'
```

The URL must use port 443, 80, 88 or 8443. `secret_token` takes 1 to 256 characters from `A-Z`, `a-z`, `0-9`, `_` and `-`. Telegram sends it back in the `X-Telegram-Bot-Api-Secret-Token` header on each request. [Telegram webhooks with a secret token](/academy/articles/telegram-bot-api-webhook-setup-secret-token/) builds the handler that checks it. The `handle` function moves over unchanged, because the webhook body is the same Update object that `getUpdates` returns.

The two delivery methods exclude each other. While a webhook is set, `getUpdates` will not work, which is why the script checks `getWebhookInfo` before polling. `deleteWebhook` switches the bot back.

## Sending limits and next steps

The loop already honors `retry_after` on `getUpdates`, but replies need pacing too. Telegram's FAQ asks bots to stay near one message per second in a chat and at most 20 per minute in a group. Across all chats, the limit is about 30 messages per second ([Bots FAQ](https://core.telegram.org/bots/faq), accessed 2026-11-04). [Telegram rate limits and 429 errors](/academy/articles/telegram-bot-api-rate-limits-flood-429/) shows how to queue for them.

Add buttons through `reply_markup`. [Inline keyboards and callback queries](/academy/articles/telegram-bot-inline-keyboards-callback-queries/) covers buttons attached to a message. A [reply keyboard that asks for a phone number or location](/academy/articles/telegram-bot-reply-keyboard-request-contact-location/) replaces the user's keyboard. [setMyCommands](/academy/articles/telegram-bot-commands-menu-setmycommands/) puts your commands in the client's menu.

*Z-API Omni team*
