TSocial TSocial
Open in Telegram
Better in TelegramOpen in Telegram

Validate Telegram Mini App initData on Your Server

· 4 min read · 18+ readers

Validate Telegram Mini App initData on Your Server: TSocial guide cover card

When a Mini App icon (grid) 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 icon 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 code icon 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

  1. Parse the string into key value pairs.
  2. Remove the hash field and keep its value.
  3. Sort the remaining pairs alphabetically by key.
  4. Join them as key=value lines separated by \n. This is the data check string. Values must be the decoded values, not the URL-encoded text.
  5. Compute secret_key = HMAC_SHA256(key = "WebAppData", message = bot_token).
  6. Compute HMAC_SHA256(key = secret_key, message = data_check_string) and write it as lowercase hex.
  7. Compare with the received hash using a constant time comparison.
  8. Check that auth_date is 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 hash before 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 WebAppData as the message (reversed).
  • Skipping the auth_date check.
  • Trusting initDataUnsafe anywhere 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

More in Build on Telegram

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

Validate Telegram Mini App initData on Your Server | TSocial