Building a Telegram Mini App inside React feels straightforward: Telegram provides a native JavaScript script, developers load it, pull the user object from window.Telegram.WebApp.initDataUnsafe.user, and render a custom storefront or checkout interface.

However, relying on initDataUnsafe for backend transactions opens a severe security vulnerability. The initDataUnsafe object is unverified front-end state. Anyone opening your Mini App in Telegram Desktop, a browser, or a custom webview can open Developer Tools or intercept network requests to override window.Telegram.WebApp.initDataUnsafe.user.id with any arbitrary user ID. If your React app sends that unverified user.id to your backend checkout endpoint, an attacker can place orders, view private data, or deplete account balances under another user's identity.

To build a secure Mini App, you must transmit the raw, untouched initData query string to your server, verify its HMAC-SHA256 signature using your Telegram Bot Token, check the payload timestamp to block replay attacks, and only then enable native UI controls like the MainButton.

Loading the Telegram SDK and Extracting Raw initData in React

Developers often choose between importing @twa-dev/sdk from npm or loading the official https://telegram.org/js/telegram-web-app.js script via an HTML script tag. Both expose the exact same global window.Telegram.WebApp object. While @twa-dev/sdk provides TypeScript definitions, the underlying object is identical.

The key structural difference lies between two properties:

  • initDataUnsafe: A parsed JavaScript object containing user metadata (id, first_name, username). It is convenient for populating non-sensitive UI elements like profile avatars before network requests complete. Never use this property for API authorization.
  • initData: A raw, URL-encoded string generated and signed by Telegram's servers containing key-value pairs (including hash and auth_date). This exact string must be forwarded to your server in an HTTP header or request body.

Here is a custom React hook that initializes the Telegram WebApp context safely, handles SSR execution environments, extracts the raw initData string, and configures native viewport parameters.

import { useEffect, useState } from 'react'; export interface TelegramUser { id: number; first_name: string; last_name?: string; username?: string; language_code?: string; } export interface WebAppInitState { isReady: boolean; initData: string; unsafeUser: TelegramUser | null; webApp: WebApp | null; } export function useTelegramWebApp(): WebAppInitState { const [state, setState] = useState<WebAppInitState>({ isReady: false, initData: '', unsafeUser: null, webApp: null, }); useEffect(() => { // Ensure window.Telegram is available (prevents SSR crashes) if (typeof window === 'undefined' || !window.Telegram?.WebApp) { return; } const tg = window.Telegram.WebApp; // Expand app to full height inside Telegram container tg.expand(); setState({ isReady: true, initData: tg.initData, unsafeUser: (tg.initDataUnsafe?.user as TelegramUser) || null, webApp: tg, }); }, []); return state; } 

If a user launches your React app outside Telegram (for example, directly in Chrome during local testing), tg.initData will be an empty string (""). Your front-end logic must detect this state early and prevent authenticated API calls when initData is missing.

Cryptographic Backend Validation of raw initData

To verify that initData originated from Telegram and was not tampered with on the client, your server must implement Telegram's exact HMAC-SHA256 verification algorithm.

The validation sequence follows these strict steps:

  1. Parse the raw initData query string into key-value pairs.
  2. Extract and remove the hash parameter from the dataset.
  3. Sort the remaining key-value pairs alphabetically by key.
  4. Format sorted pairs into a key=value format separated by newline characters ( ). This string is the data_check_string.
  5. Create a secret key by calculating an HMAC-SHA256 hash of your secret Bot Token, using the constant string "WebAppData" as the key.
  6. Calculate an HMAC-SHA256 signature of the data_check_string using the generated secret key.
  7. Compare your calculated hex signature with the received hash using a timing-safe equality check (crypto.timingSafeEqual) to mitigate timing attacks.
  8. Check the auth_date unix timestamp against the current server time to reject stale payloads.

Here is a production-ready Express.js middleware implementation in Node.js using native crypto modules:

import { Request, Response, NextFunction } from 'express'; import crypto from 'node:crypto'; interface VerifiedRequest extends Request { telegramUser?: any; } export function validateTelegramInitData(botToken: string, maxAgeSeconds: number = 86400) { return (req: VerifiedRequest, res: Response, next: NextFunction): void => { const rawInitData = req.headers['x-telegram-init-data'] as string; if (!rawInitData) { res.status(401).json({ error: 'Missing Telegram initData header' }); return; } const urlParams = new URLSearchParams(rawInitData); const hash = urlParams.get('hash'); if (!hash) { res.status(400).json({ error: 'Missing hash parameter in initData' }); return; } urlParams.delete('hash'); // Step 3 & 4: Sort alphabetically and build data_check_string const sortedParams: string[] = []; Array.from(urlParams.keys()) .sort() .forEach((key) => { sortedParams.push(`${key}=${urlParams.get(key)}`); }); const dataCheckString = sortedParams.join(' '); // Step 5: Compute secret key = HMAC-SHA256("WebAppData", botToken) const secretKey = crypto .createHmac('sha256', 'WebAppData') .update(botToken) .digest(); // Step 6: Compute calculated hash = HMAC-SHA256(dataCheckString, secretKey) const calculatedHash = crypto .createHmac('sha256', secretKey) .update(dataCheckString) .digest('hex'); // Step 7: Timing-safe comparison const hashBuffer = Buffer.from(hash, 'hex'); const calculatedBuffer = Buffer.from(calculatedHash, 'hex'); if ( hashBuffer.length !== calculatedBuffer.length || !crypto.timingSafeEqual(hashBuffer, calculatedBuffer) ) { res.status(403).json({ error: 'Invalid HMAC signature' }); return; } // Step 8: Validate timestamp freshness (auth_date) const authDateStr = urlParams.get('auth_date'); if (!authDateStr) { res.status(400).json({ error: 'Missing auth_date' }); return; } const authDate = parseInt(authDateStr, 10); const currentTime = Math.floor(Date.now() / 1000); if (currentTime - authDate > maxAgeSeconds) { res.status(403).json({ error: 'InitData payload has expired' }); return; } // Parse verified user payload and attach to request const userJson = urlParams.get('user'); if (userJson) { req.telegramUser = JSON.parse(userJson); } next(); }; } 

If an attacker modifies user.id inside their local client runtime, the backend check will recalculate calculatedHash against the modified dataCheckString. Because the attacker does not possess your private Telegram Bot Token, their modified payload will fail the crypto.timingSafeEqual comparison and trigger a 403 response.

Synchronizing React State with Native MainButton Lifecycle

Telegram's native MainButton renders outside the webview iframe directly in the native messaging client UI. Managing MainButton state inside React components requires strict event cleanup and asynchronous state handling.

Common implementation errors include:

  • Attaching event listeners inside useEffect without cleaning them up on unmount, causing duplicate order submissions when components re-render.
  • Showing MainButton before backend validation completes.
  • Calling WebApp.ready() before React finishes initial UI rendering, causing visual flickers during load.

Here is a component pattern for a secure Checkout flow. The MainButton is only configured after confirming client initialization, and network actions execute with visual feedback indicators on the native button.

import React, { useEffect, useState, useCallback } from 'react'; import { useTelegramWebApp } from './useTelegramWebApp'; interface CartItem { id: string; name: string; price: number; } export const SecureCheckout: React.FC = () => { const { isReady, initData, webApp } = useTelegramWebApp(); const [isProcessing, setIsProcessing] = useState(false); const [orderStatus, setOrderStatus] = useState<string | null>(null); const cart: CartItem[] = [ { id: 'item_101', name: 'Premium Subscription', price: 15.00 } ]; const handleCheckout = useCallback(async () => { if (!webApp || isProcessing) return; setIsProcessing(true); webApp.MainButton.showProgress(false); try { const response = await fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Telegram-Init-Data': initData, }, body: JSON.stringify({ items: cart }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || 'Checkout request failed'); } setOrderStatus('Order successfully processed!'); webApp.MainButton.hide(); webApp.HapticFeedback.notificationOccurred('success'); } catch (err: any) { setOrderStatus(`Error: ${err.message}`); webApp.HapticFeedback.notificationOccurred('error'); } finally { setIsProcessing(false); webApp.MainButton.hideProgress(); } }, [webApp, initData, cart, isProcessing]); useEffect(() => { if (!isReady || !webApp || !initData) return; const mainButton = webApp.MainButton; // Configure initial button state mainButton.setText('PAY $15.00'); mainButton.enable(); mainButton.show(); // Bind event handler mainButton.onClick(handleCheckout); // Notify Telegram that UI layout is rendered and stable webApp.ready(); // Cleanup listener on component unmount return () => { mainButton.offClick(handleCheckout); mainButton.hide(); }; }, [isReady, webApp, initData, handleCheckout]); if (!isReady) { return <div>Loading Telegram Environment...</div>; } if (!initData) { return <div>Please open this application inside Telegram.</div>; } return ( <div style={{ padding: '16px' }}> <h2>Your Cart</h2> {cart.map((item) => ( <div key={item.id}> <span>{item.name}</span> - <strong>${item.price.toFixed(2)}</strong> </div> ))} {orderStatus && <p>{orderStatus}</p>} </div> ); }; 

Production Edge Cases and Security Architecture

When running Telegram Mini Apps in production environments, implement the following security layers:

Replay Attack Prevention

The auth_date field in initData specifies when Telegram generated the authentication payload. A malicious user could copy a valid initData string from network logs and resend it days later. Setting maxAgeSeconds (e.g., 86400 seconds for 24 hours) in your backend verification middleware ensures stale authentication signatures are rejected. For high-security transactions, convert the verified initData into a short-lived HTTP-only JWT session cookie upon initial app boot, rather than passing raw initData headers on every single fetch request.

Initialization Race Conditions

Never trigger window.Telegram.WebApp.ready() inside your index HTML header or before React component trees finish mounting. Calling ready() tells Telegram's native container to hide the loading overlay. If your app calls ready() before React renders its DOM node, the user experiences a white flash or unstyled screen layout. Call ready() inside a useEffect after your state setup and MainButton listeners are attached.

Local Development and Mocking

Because window.Telegram.WebApp.initData is empty in standard web browsers, developers often hardcode mock user objects in React state during development. Avoid hardcoding mock users directly into production bundles. Use environment variables to toggle mock modes, and isolate mock behaviors so production builds strictly enforce non-empty initData signatures.

If you are expanding your Telegram bot infrastructure or building complex full-stack Mini Apps, consult BotCreator — studio that ships Telegram bots / Mini Apps.