TSocial TSocial
Open in Telegram
Better in TelegramOpen in Telegram

Set Up a Telegram Webhook with HTTPS and a Secret Token

· 4 min read · 18+ readers

Set Up a Telegram Webhook with HTTPS and a Secret Token: TSocial guide cover card

A webhook turns your server into the place Telegram delivers updates. It is efficient, but it is also a public URL that anyone on the internet can call. This guide shows how to register it, how to make sure only Telegram can use it and how to check that it works. Method names and parameters are from the Bot API documentation at core.telegram.org/bot icon bots/api, which you should check for changes.

What you need

  1. A public address that speaks code icon HTTPS with a valid certificate, for example https://bot.example.com/telegram.
  2. A route on that address that accepts POST requests with a JSON body.
  3. A long random string for the secret token.
  4. Your bot token, in an environment variable.

Telegram sends webhooks only to certain ports. The documentation lists 443, 80, 88 and 8443. Port 443 is the usual choice.

Generate a secret

The secret_token is a string of 1 to 256 characters, using letters, numbers, underscore and hyphen. Generate one with:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Store it as WEBHOOK_SECRET, separately from the bot token.

Register the webhook

curl -X POST "https://api.telegram.org/bot$BOT_TOKEN/setWebhook" \
  -H "content-type: application/json" \
  -d '{"url":"https://bot.example.com/telegram","secret_token":"'"$WEBHOOK_SECRET"'","allowed_updates":["message","callback_query"],"drop_pending_updates":true}'

Useful parameters:

  • url: the HTTPS address.
  • secret_token: Telegram will send it back with every request.
  • allowed_updates: a list of update types you want. Fewer types mean less traffic.
  • max_connections: maximum simultaneous connections, from 1 to 100. Lower it for a small server.
  • drop_pending_updates: discard updates queued while the webhook was off.

The result is {"ok":true,"result":true,"description":"Webhook was set"}.

Verify requests

When you set a secret_token, Telegram adds this header to every request:

X-Telegram-Bot-Api-Secret-Token: <your secret>

Reject any request where the header is missing or different. Here is a minimal Node server using only built-in modules:

import http from "node:http";
import crypto from "node:crypto";

const SECRET = process.env.WEBHOOK_SECRET;
const same = (a, b) => a.length === b.length && crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));

http.createServer((req, res) => {
  if (req.method !== "POST" || req.url !== "/telegram") { res.writeHead(404).end(); return; }
  const got = String(req.headers["x-telegram-bot-api-secret-token"] ?? "");
  if (!same(got, SECRET)) { res.writeHead(401).end(); return; }
  let body = "";
  req.on("data", (c) => (body += c));
  req.on("end", () => {
    res.writeHead(200).end("ok");              // answer first
    const update = JSON.parse(body);
    handle(update).catch(console.error);       // then do the work
  });
}).listen(3000);

Put a reverse proxy or a platform that terminates HTTPS in front of it. Do not expose plain HTTP to the internet.

Check the result

curl "https://api.telegram.org/bot$BOT_TOKEN/getWebhookInfo"

Read these fields: url, pending_update_count, last_error_date, last_error_message and has_custom_certificate. If pending_update_count keeps growing, your server is slow or failing. The last error message names the problem, for example a certificate error or a 5xx response.

Respond quickly and handle retries

Reply with a 2xx status as soon as you have stored or queued the update. If Telegram does not get a success response, it retries for a while, so the same update may arrive more than once. Make your handler idempotent by remembering recent update_id values.

Remove or change the webhook

curl "https://api.telegram.org/bot$BOT_TOKEN/deleteWebhook?drop_pending_updates=true"

Do this before you go back to getUpdates. Changing the URL or secret is another setWebhook call.

Security checklist

  • Secret token set and checked on every request.
  • Only the one path is routed, with POST only.
  • Request body size limited.
  • Bot token and secret kept out of logs.
  • A non-guessable URL path is a bonus, not a replacement for the secret.
  • Rate limit or firewall unknown callers if your platform allows it.

Quick checklist

  • A public HTTPS URL with a valid certificate on port 443.
  • A random secret token generated and stored separately from the bot token.
  • setWebhook called with url, secret_token and allowed_updates.
  • The server rejects any request whose header does not match.
  • A 2xx reply is sent quickly and work is done afterwards.
  • update_id is recorded to ignore duplicates.
  • getWebhookInfo shows no last error and a small pending count.
  • Tokens and secrets never appear in logs.

Rotating the secret

To change the secret token, deploy your server so that it accepts both the old and new values for a short time, call setWebhook with the new secret, check getWebhookInfo and then remove the old value. This avoids dropped updates during rotation. Do the same when you move to a new URL.

Frequently asked questions

Is the secret token required?

It is optional, but you should always use it. Without it, anyone who learns your URL can send fake updates.

Can I use a self-signed certificate?

Telegram supports it if you upload the public certificate in setWebhook. A normal certificate is simpler.

Does the update include my bot token?

No. Never expect to receive the token in an update.

What if my server was down?

Telegram keeps undelivered updates for a limited time and retries. After recovery, pending updates arrive. Use drop_pending_updates if you want to skip them.

Related guides

More in Build on Telegram

All topics: Build on Telegram · Guide index · Explore Telegram · About TSocial

Set Up a Telegram Webhook with HTTPS and a Secret Token | TSocial