Why initData exists
A Mini App is a web page that Telegram opens inside its own interface, from an inline button, the menu button, a direct link and other launch points. Once the page loads the telegram-web-app.js script, it gets a window.Telegram.WebApp object. Two fields on that object matter for security:
initData: a raw query string with the launch data. Telegram's documentation says to validate it before using it on the bot's server.initDataUnsafe: the same data already parsed into an object. The documentation warns that it should not be trusted.
The reason is simple. Your page runs on the user's device, so any JavaScript value, including initDataUnsafe.user.id, can be changed before it reaches your API. The initData string carries a hash computed by Telegram with a key derived from your bot token. Nobody without the token can produce a valid hash for modified data, so your server can tell genuine launch data from a forgery.
What is inside initData
The string is URL-encoded and follows the WebAppInitData object. Depending on how the Mini App was launched it can contain, among others:
query_id: a session identifier used withanswerWebAppQuery.user: a JSON-serializedWebAppUserwithid,first_name, optionalusername, optionallanguage_codeand more.chat_typeandchat_instance: present for Mini Apps launched from a direct link.start_param: the value passed through astartapporstartattachlink parameter.auth_date: the Unix time when the form was opened.hash: the HMAC you will verify.signature: an Ed25519 signature meant for third-party validation, covered later.
Telegram notes that WebAppInitData is empty when the Mini App is launched from a keyboard button or from inline mode. Keyboard-button Mini Apps send data back through Telegram.WebApp.sendData, which arrives at the bot as a web_app_data service message in a normal update, so it already comes through your verified bot channel.
The validation algorithm
The official procedure has four steps:
- Parse the query string and remove the
hashfield. - Build the data-check-string: every remaining field, sorted alphabetically by key, written as
key=valueand joined with a line feed (\n, 0x0A). Use the decoded values, not the percent-encoded ones. - Compute the secret key as HMAC-SHA-256 of the bot token, using the constant string
WebAppDataas the key. - Compute HMAC-SHA-256 of the data-check-string with that secret key, encode it as lowercase hex, and compare it with
hash.
Two details trip people up. First, the order of arguments in step 3: WebAppData is the HMAC key and the bot token is the message, not the other way round. Second, do not reuse verification code written for other Telegram sign-in flows without checking it against this exact recipe; the key derivation is specific to Mini Apps. If you are adding Telegram sign-in to a regular website instead of a Mini App, see Log in with Telegram on your website.
Only hash is removed for this check. The signature field, when present, stays in the data-check-string; it is excluded only in the third-party Ed25519 flow.
Finally, the documentation recommends checking auth_date to prevent the use of outdated data. A valid hash proves the data came from Telegram, not that it is recent. Pick a maximum age that fits your app, for example a short window for payments or account changes, and ask the client to reopen the Mini App when it expires.
Python implementation
This function uses only the standard library. It returns the parsed fields or raises an error:
import hashlib, hmac, json, time
from urllib.parse import parse_qsl
class InvalidInitData(Exception):
pass
def validate_init_data(init_data: str, bot_token: str, max_age: int = 3600) -> dict:
pairs = dict(parse_qsl(init_data, keep_blank_values=True, strict_parsing=True))
received_hash = pairs.pop("hash", None)
if not received_hash:
raise InvalidInitData("missing hash")
data_check_string = "\n".join(f"{k}={v}" for k, v in sorted(pairs.items()))
secret_key = hmac.new(b"WebAppData", bot_token.encode(), hashlib.sha256).digest()
expected = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, received_hash):
raise InvalidInitData("bad hash")
auth_date = int(pairs.get("auth_date", "0"))
if time.time() - auth_date > max_age:
raise InvalidInitData("expired")
if "user" in pairs:
pairs["user"] = json.loads(pairs["user"])
return pairs
hmac.compare_digest compares the two values in a way designed to resist timing attacks, which the Python documentation recommends for checking digests. Parse user as JSON only after the hash matches; until then it is just untrusted text.
Node.js implementation
The same logic with the built-in crypto module:
import crypto from "node:crypto";
export function validateInitData(initData, botToken, maxAgeSeconds = 3600) {
const params = new URLSearchParams(initData);
const hash = params.get("hash");
if (!hash) throw new Error("missing hash");
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 secretKey = crypto.createHmac("sha256", "WebAppData").update(botToken).digest();
const expected = crypto.createHmac("sha256", secretKey).update(dataCheckString).digest();
const received = Buffer.from(hash, "hex");
if (received.length !== expected.length || !crypto.timingSafeEqual(expected, received)) {
throw new Error("bad hash");
}
const authDate = Number(params.get("auth_date"));
if (!Number.isFinite(authDate) || Date.now() / 1000 - authDate > maxAgeSeconds) {
throw new Error("expired");
}
return Object.fromEntries(params);
}
crypto.timingSafeEqual throws if the two buffers have different lengths, which is why the length is checked first. Both snippets were checked against data signed with the documented algorithm before publishing, but always test against real launch data from your own bot.
Sending initData from the page
On the client, send the raw string, not the parsed object. A common pattern is an Authorization header that your API reads on every call:
const tg = window.Telegram.WebApp;
const res = await fetch("/api/profile", {
headers: { Authorization: `tma ${tg.initData}` },
});
The tma prefix is just a convention; any header name works as long as your server knows where to look. On the server, validate first, then use user.id as the identity. After a successful check you may issue your own short-lived session cookie so you do not re-validate on every request, but keep that session shorter than the auth_date window you would accept.
Validating without the bot token
Since Bot API 8.0, Telegram also signs the data with Ed25519 so that a third party, such as an analytics service or a Mini App builder, can verify it without ever seeing your token. You give them the raw initData and your bot ID. Their data-check-string starts with <bot_id>:WebAppData, a line feed, and then all fields except hash and signature, sorted and joined as before. They verify the base64url-encoded signature with the public key that Telegram publishes on the Mini Apps page, which lists separate keys for the test and production environments. Copy the key from the official page rather than from a blog, and check auth_date in this flow too.
If your own backend holds the token, the HMAC check is enough. The Ed25519 path exists so the token never has to leave your server, which matches the advice in securing bot tokens.
Mistakes to avoid
- Trusting
initDataUnsafeor a user ID sent in the request body. The only trusted identity is the one inside a validatedinitData. - Validating once in the browser. Client-side checks prove nothing; the token must never be in front-end code.
- Re-encoding values before hashing. Build the data-check-string from decoded values exactly as received. Do not re-serialize the
userJSON, because key order and spacing would change. - Skipping
auth_date. Without a freshness check, a capturedinitDatastring remains usable for as long as your code accepts it. - Using
query_idas a user identifier. It identifies a session foranswerWebAppQuery, not a person. - Treating
start_paramas trusted input. It is signed, but its content still comes from a link anyone can craft. Validate it like any other parameter; see Telegram deep links for payload design.
Hosting the Mini App and its API
Telegram requires an HTTPS URL for a Mini App (the WebAppInfo object in the Bot API asks for one), so you need a domain and a valid certificate before you can even open the page in a client. A short name from Namecheap domains, such as app.example.com for the front end and api.example.com for the backend, keeps URLs stable when you move servers. For a static front end built with plain HTML or a bundler, Namecheap hosting can serve the files, while the validation API runs next to your bot on a VPS or container host. The certificate and DNS steps are the same as for webhooks and are covered in a custom domain and HTTPS for your bot. If you want domains and basic hosting in one account, Namecheap offers both.
Checklist
- Send the raw
initDatastring to your backend on every protected request. - Remove only
hash, sort the remaining fields and join them askey=valuelines. - Derive the secret as HMAC-SHA-256 with key
WebAppDataand the bot token as message. - Compare hashes with a constant-time function.
- Reject data older than your chosen
auth_datewindow. - Parse
useronly after validation and useuser.idas the identity. - Keep the bot token on the server; give third parties the Ed25519 path instead.
Sources
- Telegram Mini Apps, initializing Mini Apps, WebAppInitData and validating data: core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
- Telegram Mini Apps, validating data for third-party use: core.telegram.org/bots/webapps#validating-data-for-third-party-use
- Telegram Bot API, WebAppInfo and answerWebAppQuery: core.telegram.org/bots/api#webappinfo
- Python documentation, hmac.compare_digest: docs.python.org/3/library/hmac.html
- Node.js documentation, crypto.timingSafeEqual: nodejs.org/api/crypto.html