Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Webhooks and Hosting

A Telegram Webhook Server

Write a secure Telegram webhook receiver in Node.js: secret token header, body size limit, fast acknowledgment, a work queue, retries and replying via the Bot API.

A Telegram webhook is just an HTTPS endpoint that accepts POST requests with an update as JSON. Writing one is easy; writing one that is safe and does not drop updates takes a little more care. This lesson builds a complete receiver with node:http only, then tests it against a stand-in "Telegram" that sends signed requests.

Reminder for this site: the demos run on 127.0.0.1 inside a sandbox, so the real setWebhook call (which needs your token and a public URL) is shown read-only.

Registering the webhook (read-only)

You tell Telegram where to send updates with one API call. Run it once, from your own machine, with your real token in an environment variable:

Terminal
curl -s "https://api.telegram.org/bot$BOT_TOKEN/setWebhook" \
  --data-urlencode "url=https://bot.example.com/telegram/hook" \
  --data-urlencode "secret_token=$WEBHOOK_SECRET" \
  --data-urlencode "allowed_updates=[\"message\",\"callback_query\"]" \
  --data-urlencode "drop_pending_updates=true"
  • url must be HTTPS on port 443, 80, 88 or 8443, with a valid certificate (a reverse proxy such as nginx or Caddy usually provides it).
  • secret_token (1-256 characters from A-Z a-z 0-9 _ -) is sent back on every request in the header X-Telegram-Bot-Api-Secret-Token. It proves the request came from Telegram.
  • allowed_updates limits which kinds of events you receive. Asking only for what you handle saves bandwidth and attack surface.

Verifying the secret

Anyone on the internet can POST to your URL. Without a check, a stranger could forge a "message from your admin". Compare the header with your secret in constant time, so timing differences do not leak how many leading characters were right.

Node.js Constant-time secret comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The complete receiver

The handler does five things in a fixed order: check method and path, check the secret, read the body with a size limit, acknowledge, then process. Cheap rejections come first.

Node.js Receiver with secret, size limit and a work queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study what each status code means:

  • 401 for a missing or wrong secret. Telegram never produces this, so any 401 is an attacker or a misconfiguration.
  • 413 and 400 for oversized or malformed bodies. Do not parse a gigabyte of JSON.
  • 200 for everything Telegram sent, even if your code later fails. A failing handler that returns 500 makes Telegram retry the same update again and again, and one poison update blocks the whole queue. Log the failure and move on.

Replying: two styles

You can reply by calling the Bot API after you acknowledge (POST https://api.telegram.org/bot<TOKEN>/sendMessage), which is the general approach. For a quick reply, Telegram also lets you return the method call as the HTTP response body: respond with Content-Type: application/json and a body like {"method":"sendMessage","chat_id":5,"text":"pong"}. That saves one request, but you cannot see whether the call succeeded, so use it only for trivial replies.

Operational checklist

  • Put the bot behind a reverse proxy with TLS and forward only the hook path.
  • Do not use the bot token in the URL path in logs you share; if you do put it there as an extra secret, redact it in access logs.
  • Use getWebhookInfo to see pending_update_count, last_error_date and last_error_message. It is the first place to look when updates stop.
  • Plan for restarts: a webhook with drop_pending_updates=false queues updates at Telegram while you are down (for up to a day or so), so you receive them when you are back.
  • When developing locally, either use polling or a tunnel; see hosting and process management.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the purpose of secret_token in setWebhook?

    Telegram echoes it in X-Telegram-Bot-Api-Secret-Token; requests without it are not from Telegram.
  2. 2. Why compare secrets with timingSafeEqual?

    A plain comparison can return earlier for wrong guesses, and timing differences can be measured.
  3. 3. Your command handler throws an exception. What should the webhook respond to Telegram?

    The update was received. Returning an error causes endless redelivery of an update that will keep failing.
  4. 4. Why keep a set of seen update_id values?

    Retries after timeouts can deliver the same update more than once. Bound the set in real code.

Summary

  • Register with setWebhook (HTTPS, secret_token, allowed_updates) and verify the secret header on every request.
  • Reject cheaply and early: method, path, secret, body size, JSON validity.
  • Acknowledge with 200 first, then process through a queue so one failure does not break the rest.
  • Deduplicate by update_id and use getWebhookInfo for diagnosis.

Next: Discord interactions endpoint and signatures