Dev.to Security 🔐 Cybersecurity 👁 0 📖 3 min read

How to Verify Telegram Mini App initData Safely in TypeScript (Zero Dependencies)

Most Telegram Mini App tutorials verify initData with a naive === hash comparison and skip timestamp checks. In production, that leaves your backend exposed to replay attacks, timing attacks, and malformed user payloads.

Most Telegram Mini App tutorials verify initData with a naive === hash comparison and skip timestamp checks. In production, that leaves your backend exposed to replay attacks, timing attacks, and malformed user payloads.

Here is the exact zero-dependency TypeScript pattern we use to validate Telegram initData cleanly before issuing any session token.

The 5 Security Checks You Should Never Skip

  1. Validate the hash format first: Reject anything that is not a valid 64-character hex string before touching crypto buffers.
  2. Sort parameters alphabetically (excluding hash): Build the data_check_string using \n separators from URLSearchParams.
  3. Derive the secret key properly: Telegram signs initData using HMAC-SHA256 with "WebAppData" as the key and your BOT_TOKEN as the message.
  4. Use crypto.timingSafeEqual: Never compare hex digests with ===.
  5. Enforce a strict auth_date window & positive user.id: Reject stale payloads older than 1 hour (3600s) and future timestamps beyond small clock skew (-60s), then verify user.id is a positive integer.

Complete TypeScript Implementation (verifyInitData.ts)


ts
import crypto from 'node:crypto';

export interface TelegramInitDataUser {
  id: number;
  first_name?: string;
  last_name?: string;
  username?: string;
  language_code?: string;
  is_premium?: boolean;
  photo_url?: string;
}

const HEX_64_REGEX = /^[0-9a-f]{64}$/i;
const MIN_AGE_SECONDS = -60;
const MAX_AGE_SECONDS = 3600;

export function verifyInitData(
  raw: string,
  botToken: string,
  nowSeconds?: number,
): TelegramInitDataUser | null {
  if (!raw || !botToken || typeof raw !== 'string' || typeof botToken !== 'string') {
    return null;
  }

  const params = new URLSearchParams(raw);
  const hash = params.get('hash');
  if (!hash || !HEX_64_REGEX.test(hash)) {
    return null;
  }

  params.delete('hash');

  const data = Array.from(params.entries())
    .sort(([keyA], [keyB]) => (keyA < keyB ? -1 : keyA > keyB ? 1 : 0))
    .map(([key, value]) => `${key}=${value}`)
    .join('\n');

  const secret = crypto.createHmac('sha256', 'WebAppData').update(botToken).digest();
  const calc = crypto.createHmac('sha256', secret).update(data).digest('hex');

  const calcBuffer = Buffer.from(calc, 'hex');
  const hashBuffer = Buffer.from(hash, 'hex');
  if (
    calcBuffer.length !== hashBuffer.length ||
    !crypto.timingSafeEqual(calcBuffer, hashBuffer)
  ) {
    return null;
  }

  const authDateRaw = params.get('auth_date');
  if (!authDateRaw || authDateRaw.trim() === '') {
    return null;
  }

  const authDate = Number(authDateRaw);
  if (!Number.isFinite(authDate)) {
    return null;
  }

  const now = nowSeconds ?? Math.floor(Date.now() / 1000);
  const age = now - authDate;
  if (age < MIN_AGE_SECONDS || age > MAX_AGE_SECONDS) {
    return null;
  }

  const userRaw = params.get('user');
  if (!userRaw) return null;

  let parsedUser: unknown;
  try {
    parsedUser = JSON.parse(userRaw);
  } catch {
    return null;
  }

  if (typeof parsedUser !== 'object' || parsedUser === null || Array.isArray(parsedUser)) {
    return null;
  }

  const record = parsedUser as Record<string, unknown>;
  const id = record.id;
  if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0) {
    return null;
  }

  const user: TelegramInitDataUser = { id };
  if (typeof record.first_name === 'string') user.first_name = record.first_name;
  if (typeof record.last_name === 'string') user.last_name = record.last_name;
  if (typeof record.username === 'string') user.username = record.username;
  if (typeof record.language_code === 'string') user.language_code = record.language_code;
  if (typeof record.is_premium === 'boolean') user.is_premium = record.is_premium;
  if (typeof record.photo_url === 'string') user.photo_url = record.photo_url;

  return user;
}
Free Source Code & Unit Tests:
You can grab this complete verifyInitData.ts implementation along with its 6 native node --test unit tests on GitHub:
• GitHub Repo
https://github.com/Arvelius-Agency/telegram-initdata-guard-ts

(If you are building a paid Telegram Mini App and don't want to wire up Stripe Checkout raw-body webhooks, TON memo indexing, plan entitlements, and an allowlisted Admin console from scratch, we also packaged our complete Fastify 5 + React 18 starter kit here:
https://arvelius.gumroad.com/l/secure-tma-devkit


📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.