# Telegram Bot API webhooks: setWebhook, secret_token, getUpdates

> Set a Telegram bot webhook with a secret_token, check the header in your handler, debug with getWebhookInfo, and know why getUpdates stops working.

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

Call `setWebhook` with an HTTPS URL on port 443, 80, 88 or 8443 and a `secret_token`. Telegram then POSTs every update to that URL with the token in the `X-Telegram-Bot-Api-Secret-Token` header, and your handler rejects any request where the header doesn't match. While the webhook is set, `getUpdates` returns nothing. The [Bot API reference](https://core.telegram.org/bots/api) says the two ways of receiving updates are mutually exclusive, so remove the webhook with `deleteWebhook` before you poll again.

## Set the webhook

Every Bot API call takes the form `https://api.telegram.org/bot<token>/METHOD_NAME`, over GET or POST, and parameters can travel as `application/json` ([Making requests](https://core.telegram.org/bots/api#making-requests)). Generate the secret first. Telegram accepts 1 to 256 characters, and only `A-Z`, `a-z`, `0-9`, `_` and `-` are allowed. A hex string fits.

```bash
SECRET_TOKEN=$(openssl rand -hex 32)

curl -X POST "https://api.telegram.org/botBOT_TOKEN/setWebhook" \
  -H "Content-Type: application/json" \
  -d "{
    \"url\": \"https://YOUR_DOMAIN/telegram/webhook\",
    \"secret_token\": \"$SECRET_TOKEN\",
    \"allowed_updates\": [\"message\", \"callback_query\"],
    \"max_connections\": 40,
    \"drop_pending_updates\": true
  }"
```

Every response carries a Boolean `ok` field, and a failure adds a human-readable `description`. Store `SECRET_TOKEN` where your handler can read it, because `getWebhookInfo` does not return it.

| Parameter | What it does ([setWebhook](https://core.telegram.org/bots/api#setwebhook)) |
| --- | --- |
| `url` | HTTPS URL that receives updates; an empty string removes the webhook |
| `certificate` | Your public key certificate, only for a self-signed setup |
| `ip_address` | Fixed IP to send to instead of the address resolved through DNS |
| `max_connections` | Simultaneous HTTPS connections, 1 to 100, default 40 |
| `allowed_updates` | Update types to receive; omit it and the previous setting stays |
| `drop_pending_updates` | `true` drops every update still waiting |
| `secret_token` | 1 to 256 characters, sent back in `X-Telegram-Bot-Api-Secret-Token` |

Two parameters behave in ways that catch people. With `allowed_updates` empty, you get every update type except `chat_member`, `message_reaction` and `message_reaction_count`. Bots that track membership or reactions have to list those types by name. And `drop_pending_updates` throws away the queue. Use it when the queue holds junk from a test, and leave it off when you move a live bot to a new server.

## What the URL must accept

Telegram's webhook guide lists the conditions, and a URL that misses one never receives an update ([Marvin's Marvellous Guide to All Things Webhook](https://core.telegram.org/bots/webhooks)). "Other ports are not supported and will not work," it says of anything outside 443, 80, 88 and 8443. A webhook "requires SSL/TLS encryption, no matter which port is used," and only TLS 1.2 and up is supported. IPv6 is not supported for webhooks, so the host needs an IPv4 address.

Requests come from the subnets `149.154.160.0/20` and `91.108.4.0/22`. The guide warns that "Our IP-range might change in the future," so an IP allowlist alone is a weak check. The secret header survives a range change.

A self-signed certificate works if you upload it in the `certificate` parameter. The guide asks for it "as multipart/form data in PEM encoded (ASCII BASE64) format".

## Check the secret in the handler

This Node.js handler compares the header in constant time, answers 200, and then processes the update. Save it as `handler.mjs` and run it behind a reverse proxy that terminates TLS on port 443.

```javascript
import http from 'node:http';
import { timingSafeEqual } from 'node:crypto';

const SECRET = Buffer.from(process.env.TELEGRAM_SECRET_TOKEN ?? '');
const seen = new Set(); // use Postgres or Redis in production

function secretMatches(header) {
  if (SECRET.length === 0 || typeof header !== 'string') return false;
  const got = Buffer.from(header);
  return got.length === SECRET.length && timingSafeEqual(got, SECRET);
}

http.createServer((req, res) => {
  if (req.method !== 'POST' || !secretMatches(req.headers['x-telegram-bot-api-secret-token'])) {
    res.writeHead(401).end();
    return;
  }
  let body = '';
  req.on('data', (chunk) => { body += chunk; });
  req.on('end', () => {
    res.writeHead(200).end();
    let update;
    try { update = JSON.parse(body); } catch { return; }
    if (seen.has(update.update_id)) return;
    seen.add(update.update_id);
    console.log(update.update_id, update.message?.text ?? '(no text)');
  });
}).listen(3000);
```

Node lowercases incoming header names, hence `x-telegram-bot-api-secret-token`. The length check comes first because `timingSafeEqual` throws on buffers of different sizes.

## Retries, duplicates and the 24-hour limit

If your endpoint answers with a status outside 2XX, Telegram will "repeat the request and give up after a reasonable amount of attempts" ([setWebhook](https://core.telegram.org/bots/api#setwebhook)). The reference gives no count and no schedule. Updates also have a ceiling on the server side. They wait until the bot receives them but "will not be kept longer than 24 hours" ([Getting updates](https://core.telegram.org/bots/api#getting-updates)). An endpoint that stays down for a day loses messages.

Retries mean the same update can arrive twice. Use `update_id` as the key. The reference describes it as a unique, sequentially increasing identifier that helps you ignore repeated updates or restore their order. It has one quirk. After about a week without updates, the next `update_id` is chosen at random. Dedupe on the exact value and never assume each id is the previous one plus one. A Postgres pattern that works for any provider's event id is in [Duplicate WhatsApp webhooks in n8n: dedupe by message id](/academy/articles/n8n-duplicate-webhooks-idempotency/).

You can also answer a webhook by putting a Bot API method in the response body. The reference adds a catch. "It's not possible to know that such a request was successful or get its result". Send replies with a separate API call if you need to log delivery.

## Debug with getWebhookInfo

```bash
curl "https://api.telegram.org/botBOT_TOKEN/getWebhookInfo"
```

The method takes no parameters and returns a `WebhookInfo` object. Read three fields first. `pending_update_count` is the "Number of updates awaiting delivery". `last_error_date` is the "Unix time for the most recent error that happened when trying to deliver an update via webhook". `last_error_message` gives that error in readable form ([getWebhookInfo](https://core.telegram.org/bots/api#getwebhookinfo)). A growing pending count with a recent error date means Telegram is reaching your URL and failing. An empty `url` means the bot is on `getUpdates` and no webhook is set.

If the error points at your handler and you use n8n as the receiver, [n8n webhook not receiving events](/academy/articles/n8n-webhook-not-receiving-production-url/) covers the test and production URL mix-up.

## Why getUpdates stops working

`getUpdates` "will not work if an outgoing webhook is set up" ([getUpdates](https://core.telegram.org/bots/api#getupdates)). To poll from a laptop during development, call `deleteWebhook` first. It takes an optional `drop_pending_updates` as well. When you poll, pass an `offset` one above the last `update_id` you processed. The reference defines the rule. "An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id". Switching back to production means calling `setWebhook` again with the same `secret_token`.

If the bot is one channel among several you run, Z-API Omni puts WhatsApp, Messenger, Instagram and Telegram in one subscription ([View documentation](https://developer.omni.z-api.io/en)).

*Z-API Omni team*
