Validate Telegram Mini App initData on Your Server
· 4 min read · 18+ readers

When a Mini App opens, Telegram gives the page a string called
initData. It contains the user's identity and a signature. If you use the user id from the browser without checking the signature, anyone can pretend to be anyone. This guide shows how to verify initData on your server using your bot token. The algorithm below follows the Mini Apps documentation at core.telegram.org/bots/webapps, which you should check against for any change.
What initData looks like
It is a URL-encoded query string, for example:
query_id=AAH...&user=%7B%22id%22%3A12345%2C%22first_name%22%3A%22Mia%22%7D&auth_date=1730000000&hash=abcdef...
Fields can include user (a JSON object), chat_instance, chat_type, start_param, auth_date and hash. The hash is a signature over all the other fields.
In the browser you read it with Telegram.WebApp.initData (the raw string) and send it to your server, usually in a header. initDataUnsafe is the same data parsed, but still unverified.
The algorithm
- Parse the string into key value pairs.
- Remove the
hashfield and keep its value. - Sort the remaining pairs alphabetically by key.
- Join them as
key=valuelines separated by\n. This is the data check string. Values must be the decoded values, not the URL-encoded text. - Compute
secret_key = HMAC_SHA256(key = "WebAppData", message = bot_token). - Compute
HMAC_SHA256(key = secret_key, message = data_check_string)and write it as lowercase hex. - Compare with the received
hashusing a constant time comparison. - Check that
auth_dateis recent.
Note the unusual order in step 5: the constant string WebAppData is the key and the bot token is the message.
Node.js example
import crypto from "node:crypto";
export function validateInitData(initData, botToken, maxAgeSeconds = 3600) {
const params = new URLSearchParams(initData);
const hash = params.get("hash");
if (!hash) return null;
params.delete("hash");
const dataCheckString = [...params.entries()]
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([k, v]) => `${k}=${v}`)
.join("\n");
const secret = crypto.createHmac("sha256", "WebAppData").update(botToken).digest();
const calc = crypto.createHmac("sha256", secret).update(dataCheckString).digest("hex");
const a = Buffer.from(calc, "hex"), b = Buffer.from(hash, "hex");
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null;
const age = Math.floor(Date.now() / 1000) - Number(params.get("auth_date") ?? 0);
if (!(age >= 0 && age <= maxAgeSeconds)) return null;
return { user: JSON.parse(params.get("user") ?? "null"), startParam: params.get("start_param"), raw: Object.fromEntries(params) };
}
URLSearchParams already decodes values, which is what the algorithm requires.
Using the result
- If it returns
null, respond with 401 and do not create a session. - If it returns a user, look up or create the account by
user.id. See connecting your backend. - Issue your own session token (for example a signed cookie or JWT) so you do not need to validate on every request, or validate on every request and keep tokens short lived.
- Never send the bot token to the browser.
Freshness and replay
A valid initData string stays valid forever unless you check auth_date. Reject strings older than your limit. An hour or a day is common, depending on how long you keep sessions. Short windows protect against someone reusing a stolen string.
Third party validation without the token
Telegram also provides an Ed25519 signature field in initData that lets a party who does not have the bot token verify the data using Telegram's public key. This is useful when you want another service to check data without sharing your token. The documentation describes how to build the data string for that case. Check it before implementing, since it differs slightly from the HMAC version.
Common mistakes
- Comparing hashes with
===(timing leaks) or comparing the wrong case. - Forgetting to remove
hashbefore building the string. - Using URL-encoded values in the data check string.
- Sorting incorrectly or not sorting at all.
- Using the token as the key and
WebAppDataas the message (reversed). - Skipping the
auth_datecheck. - Trusting
initDataUnsafeanywhere on the server. - Logging full
initData, which contains the signature and user data.
Testing
Create a test by copying real initData from a Mini App you opened yourself, in a private test environment, and run it through your function. Then change one character and confirm it fails. Never post real initData publicly.
Quick checklist
- initData sent to the server in a header, never trusted from the browser alone.
- hash removed, remaining decoded pairs sorted and joined with newlines.
- Secret derived as HMAC with key WebAppData and the bot token as message.
- Result compared in constant time.
- auth_date is recent.
- A session is issued only after validation.
- initData is not logged in full.
- Tests cover valid and tampered samples.
When validation fails
Return a generic 401, do not explain which part failed, and log only the reason code. If many real users fail suddenly, check for a token rotation, a library update that changed encoding or a proxy that rewrites headers.
Frequently asked questions
Is initData the same as the Login Widget data?
No. The Login Widget uses a different secret derivation. See which signature to verify.
Does it prove the user is the account owner?
It proves Telegram generated the data for that user opening your app. It is the standard way to authenticate in a Mini App.
How long should my sessions last?
Choose based on your risk. Shorter is safer. Re-validate when a new session starts.
Do I need this for read-only public pages?
Not for public content. Use it whenever you act as a specific user.
Related guides

Create a Telegram Mini App and Register It in BotFather
Build a minimal Telegram Mini App page, include the Telegram Web App script, host it on HTTPS and register it in BotFather with a menu button or /newapp.

Which Telegram Signature to Verify: initData, Login Widget or Webhook
Telegram uses three different ways to prove data came from it. Compare initData, the Login Widget hash and the webhook secret token, with a decision table.

Telegram Login Widget: Sign In With Telegram on a Website
Add Log in with Telegram to your website: /setdomain in BotFather, the widget script, the data you receive, server-side hash verification and common mistakes.

Keep Your Telegram Bot Token Safe (and What to Do if It Leaks)
A bot token is a password. Learn where tokens leak, how to store them, how to rotate with /revoke, how to detect misuse and a leak response checklist.

Connect Your Backend to a Telegram Bot: A Practical Architecture
How to wire a bot to your own backend: receiving updates, mapping Telegram users to accounts, queues, database design, idempotency and safe deploys.

A Telegram Webhook on AWS Lambda or a Small Server
Two ways to receive Telegram updates: an AWS Lambda function URL and a tiny Node server behind HTTPS, with secret token checks, fast replies and queues.
More in Build on Telegram
- Add a Bot as Channel Admin and Post to Your Channel
- Bot Privacy Mode and Group Admin Rights Explained
- BotFather Commands: What Each One Does
- Common Telegram Bot Errors and How to Fix Them
All topics: Build on Telegram · Guide index · Explore Telegram · About TSocial