When building a Telegram Mini App with a React frontend and a REST API backend, developer convenience often leads to catastrophic security bugs. The Telegram Mini App SDK populates a global object named window.Telegram.WebApp.initDataUnsafe, which conveniently exposes the current user's Telegram ID, first name, username, and language code.
If your React app reads initDataUnsafe.user.id and sends that raw numeric ID in JSON request payloads—or as a URL parameter—to your API endpoints, your backend is wide open to identity spoofing. Because initDataUnsafe is constructed inside the client context, any attacker can run your Mini App inside a desktop browser, open Developer Tools, override window.Telegram.WebApp.initDataUnsafe with arbitrary JSON, and impersonate any Telegram user on your system. An attacker could wipe out another user's balance, access private order histories, or create actions under another administrator's handle.
To protect your API from user ID spoofing, you must ignore initDataUnsafe on the client for authentication purposes. Instead, transmit the raw, encrypted query string available at window.Telegram.WebApp.initData to your PHP backend. Your backend must verify the cryptographic signature of this string using an HMAC-SHA256 hash derived from your Telegram Bot Token. Once verified, the backend issues a short-lived JSON Web Token (JWT) that your React client presents for all subsequent API requests.
Here is how to build a production-grade authentication flow using React, TypeScript, PHP, and JWT authentication.
Section 1: Exchanging Raw Telegram initData in React
In React, state management for authentication must handle three distinct phases: checking local storage for an existing valid JWT token, attempting a bootstrap exchange with raw initData if no token exists, and handling fallback states if the app runs outside Telegram.
Do not send initData with every standard application API request. The signature string is lengthy and requires CPU-bound HMAC recalculation on every request. Instead, perform an initial authentication handshake at startup: exchange initData for an API-native JWT token, store that token in memory or sessionStorage, and use standard Bearer token authorization for domain endpoints.
Here is an explicit React context implementation that captures window.Telegram.WebApp.initData, POSTs it to the authentication endpoint, and exposes the authenticated state to your React application.
import React, { createContext, useContext, useEffect, useState } from 'react'; interface AuthContextType { token: string | null; isAuthenticated: boolean; isLoading: boolean; error: string | null; } declare global { interface Window { Telegram?: { WebApp?: { initData: string; ready: () => void; }; }; } } const AuthContext = createContext<AuthContextType>({ token: null, isAuthenticated: false, isLoading: true, error: null, }); export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [token, setToken] = useState<string | null>(null); const [isLoading, setIsLoading] = useState<boolean>(true); const [error, setError] = useState<string | null>(null); useEffect(() => { const authenticate = async () => { const tg = window.Telegram?.WebApp; const rawInitData = tg?.initData; if (!rawInitData) { setError('App must be launched inside Telegram.'); setIsLoading(false); return; } const existingToken = sessionStorage.getItem('app_jwt'); if (existingToken) { setToken(existingToken); setIsLoading(false); tg.ready(); return; } try { const response = await fetch('/api/auth/login.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Telegram ${rawInitData}`, }, }); if (!response.ok) { const failureData = await response.json(); throw new Error(failureData.error || 'Authentication failed'); } const data = await response.json(); sessionStorage.setItem('app_jwt', data.token); setToken(data.token); // Notify Telegram that the Mini App UI is fully ready to display tg.ready(); } catch (err: any) { setError(err.message || 'Network error occurred'); } finally { setIsLoading(false); } }; authenticate(); }, []); return ( <AuthContext.Provider value={{ token, isAuthenticated: !!token, isLoading, error }}> {children} </AuthContext.Provider> ); }; export const useAuth = () => useContext(AuthContext); Notice the order of operations in the hook. window.Telegram.WebApp.ready() is only invoked after the API server successfully verifies the cryptographic signature and returns a 200 OK with the JWT token. Calling ready() earlier will flash unauthenticated UI states or trigger race conditions with child components attempting to read data before permissions are established.
Section 2: Cryptographic HMAC Verification and JWT Generation in PHP
The authentication endpoint in PHP must inspect the Authorization header, parse the incoming Telegram string, sort its key-value pairs alphabetically, and compute an HMAC-SHA256 signature using a secret key derived from your Bot Token.
Telegram’s verification protocol dictates two key operations:
- Generate an intermediate secret key using the HMAC-SHA256 hash of your bot token, with the string constant
"WebAppData"as the key. - Build the
data_check_stringby sorting all query parameters alphabetically by key (excluding thehashparameter itself) and separating pairs with newline () characters.
If the HMAC signature of data_check_string using the derived secret key matches the received hash parameter, the payload is authentic. Next, check the auth_date key to ensure the request was generated recently (e.g., within 86400 seconds), preventing replay attacks where old signed payloads are reused.
Below is a complete, standalone PHP script that performs this check, parses the embedded JSON user object, and issues a standard HS256 JWT using native PHP logic.
<?php declare(strict_types=1); header('Content-Type: application/json'); $botToken = getenv('TELEGRAM_BOT_TOKEN'); $jwtSecret = getenv('JWT_SECRET'); if (!$botToken || !$jwtSecret) { http_response_code(500); echo json_encode(['error' => 'Server misconfiguration: secret keys missing']); exit; } $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; if (!str_starts_with($authHeader, 'Telegram ')) { http_response_code(401); echo json_encode(['error' => 'Missing or invalid Authorization header']); exit; } $rawInitData = substr($authHeader, 9); parse_str($rawInitData, $authData); if (!isset($authData['hash'])) { http_response_code(400); echo json_encode(['error' => 'Missing hash parameter in initData']); exit; } $telegramHash = $authData['hash']; unset($authData['hash']); // Step 1: Sort parameters alphabetically ksort($authData); // Step 2: Form data_check_string $dataCheckArr = []; foreach ($authData as $key => $value) { $dataCheckArr[] = $key . '=' . $value; } $dataCheckString = implode(" ", $dataCheckArr); // Step 3: Derive secret key using 'WebAppData' and Telegram Bot Token $secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true); // Step 4: Calculate expected HMAC hash $calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey); // Step 5: Secure hash comparison if (!hash_equals($calculatedHash, $telegramHash)) { http_response_code(403); echo json_encode(['error' => 'Invalid initData signature. Authentication failed.']); exit; } // Step 6: Prevent replay attacks via auth_date check $authDate = (int)($authData['auth_date'] ?? 0); $currentTime = time(); $maxAgeSeconds = 86400; // 24 hours if (($currentTime - $authDate) > $maxAgeSeconds) { http_response_code(401); echo json_encode(['error' => 'Stale initData session. Re-open Mini App.']); exit; } // Extract verified user payload safely $userData = json_decode($authData['user'] ?? '{}', true); if (empty($userData['id'])) { http_response_code(400); echo json_encode(['error' => 'User object missing in validated initData']); exit; } $telegramUserId = (int)$userData['id']; // Generate JWT token $payload = [ 'iss' => 'https://api.yourdomain.com', 'sub' => $telegramUserId, 'iat' => $currentTime, 'exp' => $currentTime + (3600 * 12), // 12-hour expiration 'user' => [ 'first_name' => htmlspecialchars($userData['first_name'] ?? '', ENT_QUOTES, 'UTF-8'), 'username' => htmlspecialchars($userData['username'] ?? '', ENT_QUOTES, 'UTF-8') ] ]; function base64UrlEncode(string $data): string { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } $headerJson = json_encode(['typ' => 'JWT', 'alg' => 'HS256']); $payloadJson = json_encode($payload); $base64UrlHeader = base64UrlEncode($headerJson); $base64UrlPayload = base64UrlEncode($payloadJson); $jwtSignature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $jwtSecret, true); $base64UrlSignature = base64UrlEncode($jwtSignature); $jwtToken = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature; echo json_encode(['token' => $jwtToken, 'expires_in' => 43200]); By decoupling the initial Telegram signature validation from core REST resources, your backend executes the computational HMAC derivation only once per session. The resulting JWT provides a stateless, cryptographically secure identifier for every subsequent action.
Section 3: Protecting Domain API Endpoints with JWT Middleware
Once the frontend receives the JWT, every fetch call to domain endpoints (e.g., retrieving user profile details or submitting orders) must attach the token in standard Authorization: Bearer <jwt> format.
Here is a lightweight custom fetch wrapper in React, alongside a middleware validation function in PHP to guard domain endpoints against unauthorized access.
Client-Side HTTP Wrapper (React / TypeScript)
export async function apiFetch(endpoint: string, options: RequestInit = {}): Promise<any> { const token = sessionStorage.getItem('app_jwt'); if (!token) { throw new Error('No active token found in storage.'); } const headers = new Headers(options.headers || {}); headers.set('Authorization', `Bearer ${token}`); headers.set('Content-Type', 'application/json'); const response = await fetch(endpoint, { ...options, headers, }); if (response.status === 401) { // Session expired or invalidated on server sessionStorage.removeItem('app_jwt'); window.location.reload(); throw new Error('Session expired. Reloading session.'); } if (!response.ok) { const errorBody = await response.json().catch(() => ({ error: 'Unknown server error' })); throw new Error(errorBody.error || `HTTP error ${response.status}`); } return response.json(); } Server-Side JWT Authorization Guard (PHP Middleware)
Place this validation logic at the entrance of your protected PHP endpoints (e.g., /api/user/profile.php):
<?php declare(strict_types=1); function authenticateRequest(): int { $jwtSecret = getenv('JWT_SECRET'); $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; if (!preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) { http_response_code(401); echo json_encode(['error' => 'Missing or malformed Authorization header']); exit; } $jwt = $matches[1]; $tokenParts = explode('.', $jwt); if (count($tokenParts) !== 3) { http_response_code(401); echo json_encode(['error' => 'Invalid token structure']); exit; } list($base64Header, $base64Payload, $base64Signature) = $tokenParts; $signature = base64UrlDecode($base64Signature); $expectedSignature = hash_hmac('sha256', $base64Header . "." . $base64Payload, $jwtSecret, true); if (!hash_equals($expectedSignature, $signature)) { http_response_code(403); echo json_encode(['error' => 'JWT signature verification failed']); exit; } $payload = json_decode(base64UrlDecode($base64Payload), true); if (($payload['exp'] ?? 0) < time()) { http_response_code(401); echo json_encode(['error' => 'Token has expired']); exit; } // Return the cryptographically verified Telegram user ID return (int)$payload['sub']; } function base64UrlDecode(string $data): string { $remainder = strlen($data) % 4; if ($remainder) { $padlen = 4 - $remainder; $data .= str_repeat('=', $padlen); } return base64_decode(strtr($data, '-_', '+/')); } // Endpoint Usage Example: $userId = authenticateRequest(); // At this point, $userId is cryptographically guaranteed to be genuine. // Fetch and return order details matching ONLY this user ID. echo json_encode([ 'status' => 'success', 'userId' => $userId, 'data' => [ 'account_status' => 'active', 'role' => 'customer' ] ]); Production Notes: Edge Cases and UX Deadlocks
Telegram WebApp MainButton Binding: Do not initialize or render Telegram UI actions (such as
window.Telegram.WebApp.MainButton.show()) before your JWT exchange completes. If a user clicks theMainButtonwhile authentication is still pending, your callback logic will run without an authenticated context, triggering unhandled API rejections.Replay Attacks and Timestamp Tolerance: Always check
auth_dateon the initial login handshake. If a malicious party captures an authorized user's fullinitDatastring over an unencrypted local network or browser proxy, that raw string remains valid for cryptographic validation forever unless you enforce an explicit timestamp threshold (time() - auth_date > 86400).Handling Session Invalidation: When your PHP server returns HTTP 401 due to an expired JWT, your React frontend interceptor should clear
sessionStorageand reset the context state. The user can then automatically trigger a new handshake using freshinitDatafrom the native host frame without requiring a manual page refresh.Sanitize Payload Fields: While the
user.idinteger is signed by Telegram, string values insideuser(likefirst_nameorusername) can contain unescaped Unicode characters or HTML markup controlled by the Telegram account owner. Runhtmlspecialchars()or proper string sanitization before saving these values into your database or rendering them dynamically in your DOM to prevent cross-site scripting (XSS).
Building production-ready Telegram Mini Apps requires strict separation between client-side wrappers and server-side trust boundaries. If you need dedicated development support for complex Telegram integrations, contact BotCreator — studio that ships Telegram bots / Mini Apps.

