Imagine deploying an event booking Telegram Mini App built with Vue 3. In local testing, everything appears smooth: users select tickets, hit the action button, and transmit their order. Once deployed to production on mobile devices, two failure modes immediately crash your user experience and security model.
First, users on mobile screens experience broken layouts. The embedded webview renders in a half-expanded state, scrolling triggers full-page webview dismissal mid-touch, and dark mode users are blinded by default white background flashes. Second, developers who read user details directly from window.Telegram.WebApp.initDataUnsafe inadvertently open their backend to trivial identity spoofing. Because initDataUnsafe is unverified client side state, any user can open browser Developer Tools, alter user.id or user.is_premium, and submit unauthorized requests or hijack another account's data.
This guide demonstrates how to build a production-grade Vue 3 Telegram Mini App context. We will configure Telegram SDK binding, bind native theme updates to reactive CSS variables, synchronize viewport stability, send data reliably, and strictly validate raw initData on an Express backend using HMAC-SHA256 cryptography.
Synchronizing Viewport and Theme Engine in Vue 3
The Telegram WebApp script (https://telegram.org/js/telegram-web-app.js) injects a global window.Telegram.WebApp object into the DOM. Relying directly on global variables inside Vue components creates SSR hydration bugs, missing reactivity, and broken type definitions. Instead, we encapsulate WebApp initialization in a Vue 3 composable that exports reactive state and handles lifecycle events.
When Telegram opens a webview on iOS or Android, the initial layout height is partial. If a user swipes vertically, Telegram attempts to pull the webview down unless expand() is called. Furthermore, screen height fluctuates when virtual keyboards toggle. We must calculate --tg-viewport-height dynamically whenever the viewportChanged event fires, preventing the input fields from hiding underneath native chrome.
Create src/composables/useTelegram.ts to expose reactive theme parameters and initialize viewports properly:
import { ref, onMounted, onUnmounted } from 'vue';
interface TelegramUser {
id: number;
first_name: string;
last_name?: string;
username?: string;
language_code?: string;
is_premium?: boolean;
}
export function useTelegram() {
const tg = ref<any>(null);
const user = ref<TelegramUser | null>(null);
const colorScheme = ref<'light' | 'dark'>('light');
const viewportHeight = ref<number>(window.innerHeight);
const isExpanded = ref<boolean>(false);
const applyThemeVariables = (themeParams: Record<string, string>) => {
const root = document.documentElement;
if (themeParams.bg_color) root.style.setProperty('--tg-theme-bg-color', themeParams.bg_color);
if (themeParams.text_color) root.style.setProperty('--tg-theme-text-color', themeParams.text_color);
if (themeParams.hint_color) root.style.setProperty('--tg-theme-hint-color', themeParams.hint_color);
if (themeParams.link_color) root.style.setProperty('--tg-theme-link-color', themeParams.link_color);
if (themeParams.button_color) root.style.setProperty('--tg-theme-button-color', themeParams.button_color);
if (themeParams.button_text_color) root.style.setProperty('--tg-theme-button-text-color', themeParams.button_text_color);
if (themeParams.secondary_bg_color) root.style.setProperty('--tg-theme-secondary-bg-color', themeParams.secondary_bg_color);
};
const handleViewportChange = () => {
if (!tg.value) return;
viewportHeight.value = tg.value.viewportHeight;
isExpanded.value = tg.value.isExpanded;
document.documentElement.style.setProperty('--tg-viewport-height', `${tg.value.viewportHeight}px`);
};
const handleThemeChange = () => {
if (!tg.value) return;
colorScheme.value = tg.value.colorScheme;
applyThemeVariables(tg.value.themeParams || {});
};
onMounted(() => {
if (window.Telegram?.WebApp) {
const app = window.Telegram.WebApp;
tg.value = app;
// Signal to Telegram that the Mini App is fully rendered
app.ready();
// Force webview to fill native container height
app.expand();
colorScheme.value = app.colorScheme;
user.value = app.initDataUnsafe?.user || null;
applyThemeVariables(app.themeParams || {});
handleViewportChange();
app.onEvent('viewportChanged', handleViewportChange);
app.onEvent('themeChanged', handleThemeChange);
}
});
onUnmounted(() => {
if (tg.value) {
tg.value.offEvent('viewportChanged', handleViewportChange);
tg.value.offEvent('themeChanged', handleThemeChange);
}
});
return {
tg,
user,
colorScheme,
viewportHeight,
isExpanded
};
}
By dynamically updating --tg-viewport-height and CSS root variables, your App markup remains responsive across iOS modal adjustments, Android soft-keyboard popups, and native dark mode switching.
Transmitting Form Data via sendData and Direct API Requests
Telegram provides two main methods to send actions back to your system: Telegram.WebApp.sendData() and traditional HTTP requests (fetch or axios). Understanding when to use each is essential.
Telegram.WebApp.sendData(data) accepts a UTF-8 string up to 4096 bytes. It closes the Mini App immediately and fires a web_app_data service message back to the Telegram bot context. Crucially, sendData only works if the Mini App was opened via a keyboard button (KeyboardButton with web_app). If the Mini App was launched from an inline button (InlineKeyboardButton), an attachment menu, or a direct link (t.me/bot/app), calling sendData will fail silently or throw a runtime error.
To build a robust user flow, check if sendData is usable for simple form triggers. For complex operations or Mini Apps launched via inline keyboards, transmit the raw Telegram.WebApp.initData payload directly to your backend REST API over HTTPS.
Here is a Vue 3 registration component using Telegram's native MainButton component to trigger transmission:
<template>
<div class="booking-container">
<h2>Select Tickets</h2>
<div class="ticket-picker">
<button @click="decrement" :disabled="count <= 1">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</div>
<p v-if="errorMessage" class="error">{{ errorMessage }}</p>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useTelegram } from '../composables/useTelegram';
const { tg } = useTelegram();
const count = ref(1);
const errorMessage = ref('');
const increment = () => count.value++;
const decrement = () => {
if (count.value > 1) count.value--;
};
const handleMainButtonClick = async () => {
if (!tg.value) return;
tg.value.MainButton.showProgress(false);
errorMessage.value = '';
const payload = JSON.stringify({
ticket_count: count.value,
timestamp: Date.now()
});
// Check if sendData can be used (only in keyboard button context)
// Otherwise perform an authenticated API fetch using initData
try {
const response = await fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${tg.value.initData}`
},
body: payload
});
if (!response.ok) {
throw new Error(`Server returned HTTP ${response.status}`);
}
tg.value.close();
} catch (err: any) {
errorMessage.value = err.message || 'Checkout failed. Please try again.';
} finally {
tg.value.MainButton.hideProgress();
}
};
onMounted(() => {
if (tg.value?.MainButton) {
tg.value.MainButton.setText('CONFIRM BOOKING');
tg.value.MainButton.show();
tg.value.MainButton.onClick(handleMainButtonClick);
}
});
onUnmounted(() => {
if (tg.value?.MainButton) {
tg.value.MainButton.hide();
tg.value.MainButton.offClick(handleMainButtonClick);
}
});
</script>
<style scoped>
.booking-container {
padding: 16px;
background-color: var(--tg-theme-bg-color, #ffffff);
color: var(--tg-theme-text-color, #000000);
min-height: var(--tg-viewport-height, 100vh);
}
.ticket-picker {
display: flex;
align-items: center;
gap: 12px;
margin-top: 16px;
}
.error {
color: #ff3b30;
margin-top: 12px;
}
</style>
This pattern prevents blank screens by leveraging Telegram's native loader within MainButton while fallback handling guarantees network errors display inside the webview instead of freezing the interface.
Verifying HMAC Signatures and Preventing Session Spoofing on Node.js
Client applications should never be trusted. The window.Telegram.WebApp.initDataUnsafe object contains parsed user IDs, names, and auth timestamps, but any malicious user can alter this object in memory using devtools or custom scripts.
To establish authentic identities, your Vue frontend must pass the raw Telegram.WebApp.initData query string to your server inside the HTTP headers. The backend must recalculate the signature and compare it against the hash parameter provided in initData.
The algorithm operates as follows: 1. Parse initData into key-value pairs. 2. Extract the hash key and remove it from the payload set. 3. Sort the remaining keys alphabetically in ascending order. 4. Format sorted pairs as key=value, separated by newlines ( ). This string is the data_check_string. 5. Compute a secret key by running HMAC-SHA256 over your Telegram Bot Token using the constant string seed "WebAppData" as the key. 6. Compute the HMAC-SHA256 signature of data_check_string using the derived secret key. 7. Perform a constant-time comparison against the extracted hash string. 8. Verify that auth_date is fresh to block replay attacks.
Here is an Express controller in Node.js demonstrating strict cryptographic verification:
import { Request, Response } from 'express';
import crypto from 'crypto';
const BOT_TOKEN = process.env.BOT_TOKEN;
const MAX_SESSION_AGE_SECONDS = 86400; // 24 hours
interface VerifiedInitData {
user?: {
id: number;
first_name: string;
username?: string;
};
auth_date: number;
query_id?: string;
}
export function verifyTelegramInitData(rawInitData: string): VerifiedInitData | null {
if (!BOT_TOKEN) {
throw new Error('BOT_TOKEN environment variable is not defined.');
}
const urlParams = new URLSearchParams(rawInitData);
const hash = urlParams.get('hash');
if (!hash) {
return null;
}
urlParams.delete('hash');
// Sort remaining parameters alphabetically by key
const sortedPairs: string[] = [];
Array.from(urlParams.entries())
.sort(([a], [b]) => a.localeCompare(b))
.forEach(([key, value]) => {
sortedPairs.push(`${key}=${value}`);
});
const dataCheckString = sortedPairs.join('
');
// Derive secret key: HMAC-SHA256(botToken, "WebAppData")
const secretKey = crypto
.createHmac('sha256', 'WebAppData')
.update(BOT_TOKEN)
.digest();
// Calculate signature: HMAC-SHA256(dataCheckString, secretKey)
const calculatedHash = crypto
.createHmac('sha256', secretKey)
.update(dataCheckString)
.digest('hex');
// Constant-time check to prevent timing attacks
const hashBuffer = Buffer.from(hash, 'hex');
const calculatedBuffer = Buffer.from(calculatedHash, 'hex');
if (hashBuffer.length !== calculatedBuffer.length || !crypto.timingSafeEqual(hashBuffer, calculatedBuffer)) {
return null;
}
const authDate = parseInt(urlParams.get('auth_date') || '0', 10);
const currentTime = Math.floor(Date.now() / 1000);
// Reject payloads older than expiration threshold
if (currentTime - authDate > MAX_SESSION_AGE_SECONDS) {
return null;
}
const userString = urlParams.get('user');
const user = userString ? JSON.parse(userString) : undefined;
return {
user,
auth_date: authDate,
query_id: urlParams.get('query_id') || undefined
};
}
export async function handleCheckout(req: Request, res: Response) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or malformed authorization header' });
}
const rawInitData = authHeader.substring(7);
const session = verifyTelegramInitData(rawInitData);
if (!session || !session.user) {
return res.status(403).json({ error: 'Invalid or expired initData signature' });
}
const userId = session.user.id;
const { ticket_count } = req.body;
// Perform database updates securely using validated userId
console.log(`Processing order for verified Telegram User ID ${userId}: ${ticket_count} tickets`);
return res.status(200).json({ success: true, orderId: crypto.randomUUID() });
}
If an attacker manipulates the JSON string containing user details, the recalculation of calculatedHash will generate a hash collision failure, yielding HTTP 403 and dropping spoofed requests immediately.
Production Notes: Expiry, Keyboard Contexts, and Viewport Jitter
1. Replay Attack Mitigation: Always validate the auth_date parameter on your server. An attacker could capture a valid, signed initData payload from network traffic and re-transmit it days later to make duplicate requests. Discard signatures older than 24 hours (or shorter window based on business requirements).
2. Button Hydration Sequence: Never call MainButton.show() before Telegram.WebApp.ready(). On slower Android devices, invoking UI mutations prior to SDK handshakes can result in unrendered native buttons or frozen click listeners.
3. Viewport Resizing vs CSS Units: Do not rely on standard 100vh in mobile WebApp stylesheets. On mobile webviews, 100vh includes background areas beneath soft keyboards. Use --tg-viewport-height bound via JavaScript to ensure components shrink correctly when inputs gain focus.
4. Context Constraints of sendData: If your app is accessed via channel posts, inline buttons, or direct URLs, sendData cannot communicate back to the chat. Design your Vue architecture around HTTPS endpoints that validate initData rather than relying exclusively on bot service messages.
If you need specialized engineering assistance or custom infrastructure for high-scale Telegram deployments, work with BotCreator — studio that ships Telegram bots / Mini Apps. For low-level details on Telegram Bot API endpoints, review