<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Arvelius Agency </title>
    <description>The latest articles on DEV Community by Arvelius Agency  (@arveliusagency).</description>
    <link>https://dev.to/arveliusagency</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4269222%2F215bc1b3-86cc-4bf4-a42f-5c4f0299e335.png</url>
      <title>DEV Community: Arvelius Agency </title>
      <link>https://dev.to/arveliusagency</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/arveliusagency"/>
    <language>en</language>
    <item>
      <title>How to Verify Telegram Mini App initData Safely in TypeScript (Zero Dependencies)</title>
      <dc:creator>Arvelius Agency </dc:creator>
      <pubDate>Fri, 27 Nov 2026 15:09:18 +0000</pubDate>
      <link>https://dev.to/arveliusagency/how-to-verify-telegram-mini-app-initdata-safely-in-typescript-zero-dependencies-5g9a</link>
      <guid>https://dev.to/arveliusagency/how-to-verify-telegram-mini-app-initdata-safely-in-typescript-zero-dependencies-5g9a</guid>
      <description>&lt;p&gt;Most Telegram Mini App tutorials verify &lt;code&gt;initData&lt;/code&gt; with a naive &lt;code&gt;===&lt;/code&gt; hash comparison and skip timestamp checks. In production, that leaves your backend exposed to replay attacks, timing attacks, and malformed user payloads.&lt;/p&gt;

&lt;p&gt;Here is the exact zero-dependency TypeScript pattern we use to validate Telegram &lt;code&gt;initData&lt;/code&gt; cleanly before issuing any session token.&lt;/p&gt;




&lt;h3&gt;
  
  
  The 5 Security Checks You Should Never Skip
&lt;/h3&gt;

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




&lt;h3&gt;
  
  
  Complete TypeScript Implementation (&lt;code&gt;verifyInitData.ts&lt;/code&gt;)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
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]) =&amp;gt; (keyA &amp;lt; keyB ? -1 : keyA &amp;gt; keyB ? 1 : 0))
    .map(([key, value]) =&amp;gt; `${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 &amp;lt; MIN_AGE_SECONDS || age &amp;gt; 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&amp;lt;string, unknown&amp;gt;;
  const id = record.id;
  if (typeof id !== 'number' || !Number.isInteger(id) || id &amp;lt;= 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 &amp;amp; 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


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>typescript</category>
      <category>telegram</category>
      <category>node</category>
      <category>security</category>
    </item>
  </channel>
</rss>
