Validating Telegram Mini App initData in Node.js without a library
A Telegram Mini App receives the user's identity in Telegram.WebApp.initData: a query string with user, auth_date, query_id and a hash. The client can send anything it likes, so the server has to check that hash before i
A Telegram Mini App receives the user's identity in Telegram.WebApp.initData: a query string with user, auth_date, query_id and a hash. The client can send anything it likes, so the server has to check that hash before it trusts a single field. Node's crypto module is all it takes.
How Telegram signs the data
The algorithm is in the Telegram Mini Apps documentation:
- Take every field except
hash, sort them by key and join them askey=valuelines with\n. That is the data-check-string. - The secret key is HMAC-SHA256 of the bot token, with the string
WebAppDataas the key. - The expected hash is HMAC-SHA256 of the data-check-string with that secret key, in hex.
The order in step 2 trips people up. WebAppData is the HMAC key and the bot token is the message, not the other way round.
The check
import { createHmac, timingSafeEqual } from "node:crypto";
export function checkInitData(initData, botToken, maxAgeSeconds = 3600) {
const params = new URLSearchParams(initData);
const hash = params.get("hash");
if (!hash) return { ok: false, reason: "no hash" };
params.delete("hash");
const dataCheckString = [...params.entries()]
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, value]) => `${key}=${value}`)
.join("\n");
const secretKey = createHmac("sha256", "WebAppData").update(botToken).digest();
const expected = createHmac("sha256", secretKey).update(dataCheckString).digest();
const received = Buffer.from(hash, "hex");
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
return { ok: false, reason: "bad hash" };
}
const authDate = Number(params.get("auth_date"));
if (!Number.isFinite(authDate) || Date.now() / 1000 - authDate > maxAgeSeconds) {
return { ok: false, reason: "expired" };
}
return { ok: true, user: JSON.parse(params.get("user") || "null") };
}
Three details matter here.
URLSearchParams decodes the values. The data-check-string uses the decoded values, so the user field goes in as JSON text, not as %7B%22id%22….
timingSafeEqual throws when the buffers differ in length, which is why the length check comes first. A plain === on hex strings also works in practice, but the constant-time compare costs nothing.
auth_date is the only protection against replay. A valid initData stays valid forever as far as the hash is concerned, so the age limit is yours to choose. An hour suits a session start. A payment confirmation deserves a much shorter window.
Testing without a real bot
You do not need Telegram to test this. Sign a sample the same way Telegram does and check that tampering breaks it:
import assert from "node:assert/strict";
import { createHmac } from "node:crypto";
function sign(fields, botToken) {
const dcs = Object.keys(fields).sort().map((k) => `${k}=${fields[k]}`).join("\n");
const secretKey = createHmac("sha256", "WebAppData").update(botToken).digest();
const hash = createHmac("sha256", secretKey).update(dcs).digest("hex");
return new URLSearchParams({ ...fields, hash }).toString();
}
const token = "123456:TEST-TOKEN";
const fields = {
auth_date: String(Math.floor(Date.now() / 1000)),
query_id: "AAHdF6IQAAAAAN0XohDhrOrc",
user: JSON.stringify({ id: 279058397, first_name: "Test", language_code: "ru" }),
};
const initData = sign(fields, token);
assert.equal(checkInitData(initData, token).ok, true);
assert.equal(checkInitData(initData, "123456:OTHER").reason, "bad hash");
assert.equal(checkInitData(initData.replace("Test", "Evil"), token).reason, "bad hash");
const old = sign({ ...fields, auth_date: String(Math.floor(Date.now() / 1000) - 7200) }, token);
assert.equal(checkInitData(old, token).reason, "expired");
All four assertions pass on Node 24. The third one is the useful one: changing one character of the user's name invalidates the hash.
Where to run it
Run the check on every request that acts on the user's identity, not once at app start. The Mini App sends initData along with each API call, and the server reads the user id only from a payload that passed the check. The bot token never leaves the server.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.