Building an e-commerce shop inside a Telegram Mini App using Next.js App Router presents distinct architectural challenges that traditional web applications never encounter. Combining React's declarative state model with Telegram's imperative webview SDK often introduces silent runtime failures. Hydration mismatches break cold starts, stale closures in React hooks cause native UI controls to submit empty carts, and missing server-side cryptographic validation exposes order endpoints to price spoofing.
Furthermore, Telegram's embedded webview environment behaves inconsistently across operating systems. iOS Safari webviews introduce spring-bounce viewport shifts and collapsible header spaces that obscure bottom action elements. Telegram Desktop renders within a rigid modal frame with unique window focus behaviors and script loading lifecycle constraints.
In this walkthrough, we will construct a production-ready checkout pipeline in Next.js App Router. We will isolate Telegram SDK initialization from Server-Side Rendering (SSR), synchronize native Telegram buttons with dynamic React state, validate cryptographically signed initData payloads in API routes, and resolve cross-platform webview glitches.
Resolving SSR Hydration Breaks and Platform Viewport Variance
Next.js App Router evaluates server components by default during SSR and build-time static generation. Telegram's runtime context object, window.Telegram.WebApp, exists exclusively inside the client webview environment after the Telegram script finishes loading. Accessing window.Telegram during initial server evaluation causes ReferenceError crashes or severe React hydration failures where rendered HTML mismatches client expectations.
To handle initialization safely, encapsulate Telegram SDK integration inside a dedicated custom hook. This hook defers execution until client-side hydration completes, verifies the presence of window.Telegram.WebApp, locks the viewport height, and notifies the host application that the app is ready for display.
On iOS webviews, dragging lists or scrolling to page bounds can cause the webview frame to collapse into a minimized state. Calling tg.expand() immediately upon mounting ensures the Mini App fills the complete modal height across both mobile devices and desktop windows.
// hooks/useTelegram.ts
'use client';
import { useEffect, useState } from 'react';
export interface TelegramUser {
id: number;
first_name: string;
last_name?: string;
username?: string;
language_code?: string;
}
export interface WebAppInitData {
query_id?: string;
user?: TelegramUser;
auth_date: number;
hash: string;
}
export function useTelegram() {
const [webApp, setWebApp] = useState<any>(null);
const [isReady, setIsReady] = useState(false);
const [user, setUser] = useState<TelegramUser | null>(null);
useEffect(() => {
if (typeof window === 'undefined') return;
const tg = (window as any).Telegram?.WebApp;
if (!tg) return;
tg.ready();
tg.expand();
// Lock viewport to prevent erratic swipe-down dismiss behavior on mobile
if (tg.isVerticalSwipesEnabled !== undefined) {
tg.isVerticalSwipesEnabled = false;
}
setWebApp(tg);
setIsReady(true);
if (tg.initDataUnsafe?.user) {
setUser(tg.initDataUnsafe.user);
}
}, []);
return {
webApp,
isReady,
user,
initData: webApp?.initData || '',
};
}
Validating WebApp initData Integrity in Next.js Route Handlers
A critical vulnerability in Mini App storefronts is accepting user information or price calculations directly from client-side state. Front-end memory can be manipulated via browser developer tools or intercepted webview calls. Relying on initDataUnsafe or parsing price totals from a POST request body allows attackers to construct unpaid transactions or impersonate other user IDs.
Telegram addresses this by providing window.Telegram.WebApp.initData, an URL-encoded string containing user metadata signed with your Telegram Bot Token. Your front-end must send this raw string in an Authorization header when placing orders.
The Next.js App Router API route must unpack and verify the HMAC-SHA-256 signature using the following steps: 1. Parse the raw initData string into key-value query parameters. 2. Extract the received hash parameter and remove it from the working dataset. 3. Sort the remaining keys alphabetically into key=value format joined by newline characters ( ). 4. Generate a secret key by hashing the bot token string with the key "WebAppData" using HMAC-SHA-256. 5. Hash the joined data check string using the generated secret key. 6. Verify that the calculated hash matches the received hash parameter using constant-time string comparison.
// app/api/checkout/route.ts
import { NextResponse } from 'next/server';
import crypto from 'crypto';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
function verifyTelegramInitData(initDataString: string, botToken: string): { isValid: boolean; userData?: any; authDate?: number } {
const urlParams = new URLSearchParams(initDataString);
const hash = urlParams.get('hash');
if (!hash) return { isValid: false };
urlParams.delete('hash');
const paramsArray: string[] = [];
urlParams.forEach((val, key) => {
paramsArray.push(`${key}=${val}`);
});
paramsArray.sort();
const dataCheckString = paramsArray.join('
');
// Step 1: Calculate secret key using HMAC-SHA-256 with "WebAppData" constant
const secretKey = crypto
.createHmac('sha256', 'WebAppData')
.update(botToken)
.digest();
// Step 2: Calculate data hash using generated secret key
const calculatedHash = crypto
.createHmac('sha256', secretKey)
.update(dataCheckString)
.digest('hex');
// Step 3: Timing-safe comparison to protect against side-channel timing attacks
const isValid = crypto.timingSafeEqual(
Buffer.from(calculatedHash, 'hex'),
Buffer.from(hash, 'hex')
);
if (!isValid) return { isValid: false };
const userString = urlParams.get('user');
const userData = userString ? JSON.parse(userString) : null;
const authDate = parseInt(urlParams.get('auth_date') || '0', 10);
return { isValid, userData, authDate };
}
export async function POST(request: Request) {
try {
const authHeader = request.headers.get('Authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return NextResponse.json({ error: 'Missing initData authorization header' }, { status: 401 });
}
const rawInitData = authHeader.substring(7);
const botToken = process.env.TELEGRAM_BOT_TOKEN;
if (!botToken) {
return NextResponse.json({ error: 'Server misconfiguration: BOT_TOKEN missing' }, { status: 500 });
}
const { isValid, userData, authDate } = verifyTelegramInitData(rawInitData, botToken);
if (!isValid || !userData) {
return NextResponse.json({ error: 'Invalid HMAC signature in initData' }, { status: 403 });
}
// Reject payloads older than 24 hours (86400 seconds) to mitigate replay attacks
const now = Math.floor(Date.now() / 1000);
if (authDate && now - authDate > 86400) {
return NextResponse.json({ error: 'Stale initData session expired' }, { status: 401 });
}
const body = await request.json();
const items: CartItem[] = body.items;
if (!items || !Array.isArray(items) || items.length === 0) {
return NextResponse.json({ error: 'Cart cannot be empty' }, { status: 400 });
}
// In a real implementation, re-calculate item prices against DB instead of trusting body prices
const orderId = `ORD-${crypto.randomBytes(4).toString('hex').toUpperCase()}`;
return NextResponse.json({
success: true,
orderId,
userTelegramId: userData.id,
status: 'pending_payment'
});
} catch (err: any) {
return NextResponse.json({ error: err.message || 'Internal server error' }, { status: 500 });
}
}
Binding MainButton to Dynamic Cart State Without React Closure Bugs
Telegram's UI framework provides a native fixed footer button (window.Telegram.WebApp.MainButton). Connecting this button to React state creates a common closure trap. If you attach an event handler to MainButton.onClick inside a component mount effect without tracking state changes, the handler captures a stale closure of the initial empty cart array. When the customer taps "Checkout", the handler sends an empty payload.
To fix this, maintain a reference (useRef) to the current cart state, or detach and re-attach event listeners on state transitions using MainButton.offClick(). The following implementation keeps the native button synchronized with item count and pricing while preserving fresh state inside click handlers.
// components/CartCheckout.tsx
'use client';
import React, { useEffect, useRef, useState } from 'react';
import { useTelegram } from '../hooks/useTelegram';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
export function CartCheckout() {
const { webApp, initData } = useTelegram();
const [cart, setCart] = useState<CartItem[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
// Keep a mutable ref of the cart to avoid closure trap inside native event listeners
const cartRef = useRef(cart);
cartRef.current = cart;
const totalAmount = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
const handleAddToCart = (product: Omit<CartItem, 'quantity'>) => {
setCart((prev) => {
const existing = prev.find((item) => item.id === product.id);
if (existing) {
return prev.map((item) =>
item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
);
}
return [...prev, { ...product, quantity: 1 }];
});
};
const executeCheckout = async () => {
const currentCart = cartRef.current;
if (currentCart.length === 0 || isSubmitting) return;
setIsSubmitting(true);
if (webApp?.MainButton) {
webApp.MainButton.showProgress();
}
try {
const res = await fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${initData}`,
},
body: JSON.stringify({ items: currentCart }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || 'Checkout process failed');
}
if (webApp) {
webApp.close();
}
} catch (err: any) {
if (webApp) {
webApp.showAlert(err.message || 'An unexpected error occurred during checkout.');
}
} finally {
setIsSubmitting(false);
if (webApp?.MainButton) {
webApp.MainButton.hideProgress();
}
}
};
useEffect(() => {
if (!webApp?.MainButton) return;
const mainButton = webApp.MainButton;
if (cart.length > 0) {
mainButton.setText(`CHECKOUT ($${totalAmount.toFixed(2)})`);
mainButton.show();
mainButton.enable();
} else {
mainButton.hide();
}
// Re-bind handler to guarantee callback accesses fresh state context
mainButton.onClick(executeCheckout);
return () => {
mainButton.offClick(executeCheckout);
};
}, [cart, totalAmount, webApp]);
return (
<div style={{ padding: '16px', color: 'var(--tg-theme-text-color, #000)' }}>
<h2>Store Catalog</h2>
<button
style={{
padding: '8px 16px',
background: 'var(--tg-theme-button-color, #0088cc)',
color: 'var(--tg-theme-button-text-color, #fff)',
border: 'none',
borderRadius: '4px',
}}
onClick={() => handleAddToCart({ id: 'p-1', name: 'Premium Subscription', price: 19.99 })}
>
Add Premium ($19.99)
</button>
<div style={{ marginTop: '24px' }}>
<h3>Cart Summary ({cart.reduce((a, b) => a + b.quantity, 0)} items)</h3>
{cart.map((item) => (
<div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', margin: '8px 0' }}>
<span>{item.name} (x{item.quantity})</span>
<span>${(item.price * item.quantity).toFixed(2)}</span>
</div>
))}
</div>
</div>
);
}
Production Notes: Replay Mitigation and Native Telegram WebView Bugs
When pushing Next.js App Router Mini Apps to production, subtle host client edge cases can degrade performance or compromise security if left unhandled.
### Replay Prevention and Auth Date Verification Signing initData with HMAC ensures message integrity, but it does not prevent an attacker from stealing a valid initData query string and resubmitting it repeatedly to trigger duplicate processing. Always extract auth_date inside your Next.js route handlers and compare it against the server's current timestamp (Math.floor(Date.now() / 1000)). If the delta exceeds your threshold (e.g., 86400 seconds for storefront sessions, or 300 seconds for instant payment authorizations), reject the request with HTTP 401.
### WebApp.ready() Invocation Timing Never call window.Telegram.WebApp.ready() before critical DOM elements mount or before Next.js dynamic imports resolve. Executing ready() signals to Telegram that it can tear down the native loading overlay. If your app calls ready() before client components settle, the user experiences a white flash or an unstyled content shift. Conversely, failing to execute ready() within a reasonable timeframe causes Telegram Desktop to keep a persistent loading spinner active over the frame.
### Keyboard Inset Viewport Shifts on iOS On iOS Telegram clients, focusing text fields causes the software keyboard to push the webview container upward. iOS webviews frequently fail to reset window.innerHeight when the keyboard dismisses, leaving blank white space at the bottom of the Mini App interface. To fix this, attach a blur listener to form inputs that forces a layout refresh:
const handleInputBlur = () => {
window.scrollTo(0, 0);
if ((window as any).Telegram?.WebApp?.expand) {
(window as any).Telegram.WebApp.expand();
}
};
### Native BackButton Route Synchronization When utilizing Next.js client-side routing (next/navigation), sync route navigation with native Telegram back buttons. Display window.Telegram.WebApp.BackButton when users navigate away from the index route, and bind router.back() to BackButton.onClick(). Ensure you call BackButton.hide() during unmount to prevent ghost back buttons from remaining visible on subsequent bot interactions.
Engineers building production Telegram applications or scaling complex bot architectures can partner with specialized development teams like BotCreator to implement end-to-end Mini App authentication, payment webhooks, and secure backend integrations.