DEV Community

Serhii
Serhii

Posted on Originally published at botservice.biz

Fix Viewport Shifts and Broken MainButton Checkouts in Next.js Telegram Mini App Shops

Building an e-commerce catalog inside a Telegram Mini App using Next.js App Router seems straightforward until you run it across real clients. On iOS, fixed UI containers slide under Telegram's bottom bar, dynamic viewport height collapses when the software keyboard opens, and native scroll rubber-banding breaks single-page checkout flows. On Telegram Desktop, window resizes break fixed aspect ratios, while the native bottom action button (MainButton) frequently triggers stale callbacks due to React state closure drift.

More critically, relying on frontend state or raw client-side prices during checkout allows users to modify payloads via local WebInspector sessions or intercepted network packets. If your server trusts product totals sent from the browser instead of recalculating item pricing from an authoritative database, users can purchase high-value catalog items for arbitrary amounts.

This guide demonstrates how to build a resilient storefront using Next.js 14+ App Router, TypeScript, and the Telegram WebApp SDK. You will implement custom hooks to stabilize iOS and Desktop WebViews, synchronize React cart state with the native MainButton without stale event handlers, and securely issue native Telegram invoices through a server-validated Next.js Route Handler.

Section 1: Stabilize Viewport Height and Native Navigation

Telegram renders Mini Apps inside an embedded WebView wrapper. On iOS, standard CSS properties like 100vh or 100dvh do not map correctly to the visible canvas because Telegram controls the top header and bottom chrome. If a user swipes or scrolls near the bounds, the entire app bounces, revealing the Telegram chat UI beneath. Furthermore, as users switch between mobile and desktop clients, layout hooks fail if they assume fixed dimensions.

To resolve this, your application must call Telegram.WebApp.expand() immediately upon mounting, bind Telegram's native CSS variables (--tg-viewport-height and --tg-viewport-stable-height) to document roots, and synchronize Next.js router history with Telegram's native BackButton.

The hook below initializes the Telegram WebApp SDK, manages viewport resize listeners, sets application color variables, and hooks into Next.js navigation.

// hooks/useTelegramSdk.ts
'use client';

import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';

interface TelegramThemeParams {
  bg_color?: string;
  text_color?: string;
  hint_color?: string;
  link_color?: string;
  button_color?: string;
  button_text_color?: string;
  secondary_bg_color?: string;
}

interface TelegramWebApp {
  ready: () => void;
  expand: () => void;
  close: () => void;
  isExpanded: boolean;
  viewportHeight: number;
  viewportStableHeight: number;
  themeParams: TelegramThemeParams;
  BackButton: {
    show: () => void;
    hide: () => void;
    onClick: (cb: () => void) => void;
    offClick: (cb: () => void) => void;
  };
  MainButton: {
    text: string;
    color: string;
    textColor: string;
    isVisible: boolean;
    isActive: boolean;
    isProgressVisible: boolean;
    setText: (text: string) => void;
    show: () => void;
    hide: () => void;
    enable: () => void;
    disable: () => void;
    showProgress: (leaveActive?: boolean) => void;
    hideProgress: () => void;
    onClick: (cb: () => void) => void;
    offClick: (cb: () => void) => void;
  };
  openInvoice: (url: string, callback?: (status: string) => void) => void;
  initData: string;
}

declare global {
  interface Window {
    Telegram?: {
      WebApp: TelegramWebApp;
    };
  }
}

export function useTelegramSdk() {
  const [isReady, setIsReady] = useState(false);
  const [webApp, setWebApp] = useState<TelegramWebApp | null>(null);
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    const tg = window.Telegram?.WebApp;
    if (!tg) return;

    tg.ready();
    tg.expand();

    // Prevent vertical drag gestures from closing the app on mobile
    if ('isVerticalSwipesEnabled' in tg) {
      (tg as unknown as { isVerticalSwipesEnabled: boolean }).isVerticalSwipesEnabled = false;
    }

    setWebApp(tg);
    setIsReady(true);

    const handleViewportChange = () => {
      document.documentElement.style.setProperty(
        '--tg-viewport-height',
        `${tg.viewportHeight}px`
      );
      document.documentElement.style.setProperty(
        '--tg-viewport-stable-height',
        `${tg.viewportStableHeight}px`
      );
    };

    handleViewportChange();
    window.addEventListener('resize', handleViewportChange);

    return () => {
      window.removeEventListener('resize', handleViewportChange);
    };
  }, []);

  useEffect(() => {
    if (!webApp) return;

    const handleBackClick = () => {
      router.back();
    };

    if (pathname !== '/') {
      webApp.BackButton.show();
      webApp.BackButton.onClick(handleBackClick);
    } else {
      webApp.BackButton.hide();
    }

    return () => {
      webApp.BackButton.offClick(handleBackClick);
    };
  }, [pathname, webApp, router]);

  return { isReady, webApp };
}
Enter fullscreen mode Exit fullscreen mode

By injecting dynamic viewport height variables into CSS custom properties, you can style main containers with height: var(--tg-viewport-height, 100vh). This prevents layout shifts when mobile software keyboards open or when Telegram's chrome expands.

Section 2: Bind Cart State to Native MainButton Without Memory Leaks

Standard web applications render sticky bottom panels for checkout buttons. In Telegram Mini Apps, native mobile chrome overlays the bottom portion of the web container. Attempting to render floating DOM buttons at the bottom of the screen often leads to unclickable elements or layout jumping on mobile Safari.

Telegram provides a native MainButton fixed at the bottom of the client UI. However, binding React state (such as item counts or total price) to MainButton requires careful event handler teardown. If you attach a click handler inside useEffect without cleaning it up or without referencing current React state via mutable refs, clicking MainButton will trigger a checkout with stale cart data.

The component below renders a product listing, updates cart state, and updates the native MainButton UI dynamically. It uses a useRef hook to guarantee that the MainButton click callback always executes against the latest state array without re-attaching listeners on every single render.

// components/ShopCatalog.tsx
'use client';

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useTelegramSdk } from '../hooks/useTelegramSdk';

export interface Product {
  id: string;
  title: string;
  price: number; // In cents or smallest currency unit
}

const CATALOG: Product[] = [
  { id: 'prod_1', title: 'Developer Coffee Mug', price: 1500 },
  { id: 'prod_2', title: 'Mechanical Keyboard', price: 12000 },
  { id: 'prod_3', title: 'Dark Mode Sticker Pack', price: 500 },
];

export function ShopCatalog() {
  const { isReady, webApp } = useTelegramSdk();
  const [cart, setCart] = useState<Record<string, number>>({});
  const cartRef = useRef(cart);
  cartRef.current = cart;

  const calculateTotal = useCallback(() => {
    return Object.entries(cart).reduce((sum, [id, qty]) => {
      const item = CATALOG.find((p) => p.id === id);
      return sum + (item ? item.price * qty : 0);
    }, 0);
  }, [cart]);

  const handleCheckout = useCallback(async () => {
    if (!webApp) return;

    const currentCart = cartRef.current;
    const items = Object.entries(currentCart)
      .filter(([, qty]) => qty > 0)
      .map(([id, quantity]) => ({ id, quantity }));

    if (items.length === 0) return;

    webApp.MainButton.showProgress(true);
    webApp.MainButton.disable();

    try {
      const response = await fetch('/api/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          initData: webApp.initData,
          items,
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.invoiceLink) {
        throw new Error(data.error || 'Failed to generate checkout invoice');
      }

      webApp.MainButton.hideProgress();
      webApp.MainButton.enable();

      // Open native Telegram payment popup
      webApp.openInvoice(data.invoiceLink, (status) => {
        if (status === 'paid') {
          setCart({});
          webApp.MainButton.hide();
          alert('Payment successful! Your order is being processed.');
        } else if (status === 'failed') {
          alert('Payment failed or was cancelled.');
        }
      });
    } catch (err) {
      console.error('Checkout error:', err);
      webApp.MainButton.hideProgress();
      webApp.MainButton.enable();
      alert('Could not initiate checkout. Please try again.');
    }
  }, [webApp]);

  useEffect(() => {
    if (!webApp) return;

    const totalCents = calculateTotal();
    const hasItems = totalCents > 0;

    if (hasItems) {
      const formattedTotal = (totalCents / 100).toFixed(2);
      webApp.MainButton.setText(`PAY $${formattedTotal}`);
      webApp.MainButton.show();
      webApp.MainButton.enable();
    } else {
      webApp.MainButton.hide();
    }
  }, [cart, webApp, calculateTotal]);

  useEffect(() => {
    if (!webApp) return;

    const onMainButtonClick = () => {
      handleCheckout();
    };

    webApp.MainButton.onClick(onMainButtonClick);

    return () => {
      webApp.MainButton.offClick(onMainButtonClick);
    };
  }, [webApp, handleCheckout]);

  const updateQuantity = (id: string, delta: number) => {
    setCart((prev) => {
      const current = prev[id] || 0;
      const next = Math.max(0, current + delta);
      if (next === 0) {
        const copy = { ...prev };
        delete copy[id];
        return copy;
      }
      return { ...prev, [id]: next };
    });
  };

  if (!isReady) {
    return <div style={{ padding: '16px', color: '#888' }}>Initializing Store...</div>;
  }

  return (
    <div style={{ padding: '16px', maxWidth: '600px', margin: '0 auto' }}>
      <h1 style={{ fontSize: '20px', marginBottom: '16px' }}>Mini App Shop</h1>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
        {CATALOG.map((product) => {
          const qty = cart[product.id] || 0;
          return (
            <div
              key={product.id}
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                padding: '12px',
                borderRadius: '8px',
                border: '1px solid rgba(128,128,128,0.2)',
              }}
            >
              <div>
                <div style={{ fontWeight: 'bold' }}>{product.title}</div>
                <div style={{ fontSize: '14px', color: '#666' }}>
                  ${(product.price / 100).toFixed(2)}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                {qty > 0 && (
                  <button
                    onClick={() => updateQuantity(product.id, -1)}
                    style={{ padding: '6px 12px', borderRadius: '4px' }}
                  >
                    -
                  </button>
                )}
                {qty > 0 && <span>{qty}</span>}
                <button
                  onClick={() => updateQuantity(product.id, 1)}
                  style={{ padding: '6px 12px', borderRadius: '4px' }}
                >
                  +
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

When handleCheckout fires, webApp.MainButton.showProgress(true) provides immediate feedback to the user and freezes secondary input. If an API failure occurs, webApp.MainButton.hideProgress() re-enables interactive controls.

Section 3: Server-Side HMAC Validation and Invoice Generation

Client applications should never transmit final order amounts to backend payment routes. An attacker can modify network payloads to submit a price of $0.01 for an expensive product. Furthermore, the endpoint must verify that incoming requests originate from a legitimate Telegram user session and not an external script spoofing raw user identifiers.

When a Mini App launches, Telegram provides a cryptographically signed query string in window.Telegram.WebApp.initData. The server must:

  1. Parse initData into key-value pairs.
  2. Extract the hash parameter.
  3. Verify the signature by constructing a data_check_string (alphabetically sorted key=value pairs joined by newlines, excluding hash).
  4. Compute HMAC-SHA256 of the bot token against the constant key WebAppData, and use that derived key to calculate the final HMAC-SHA256 of data_check_string.
  5. Assert that calculated hash equals the client-provided hash.
  6. Reject sessions where auth_date is older than 3600 seconds (to prevent replay attacks).
  7. Look up catalog item IDs in a secure database or authoritative dictionary, calculate true totals, and invoke Telegram's createInvoiceLink Bot API method.

Here is the implementation using Next.js App Router API routes (app/api/checkout/route.ts).

// app/api/checkout/route.ts
import { NextResponse } from 'next/server';
import crypto from 'crypto';

interface ClientItem {
  id: string;
  quantity: number;
}

const SERVER_CATALOG: Record<string, { title: string; price: number; description: string }> = {
  prod_1: { title: 'Developer Coffee Mug', price: 1500, description: 'Ceramic 11oz mug' },
  prod_2: { title: 'Mechanical Keyboard', price: 12000, description: 'RGB Mechanical Keyboard' },
  prod_3: { title: 'Dark Mode Sticker Pack', price: 500, description: 'Vinyl laptop stickers' },
};

function verifyTelegramInitData(rawInitData: string, botToken: string): { isValid: boolean; user?: unknown } {
  try {
    const urlParams = new URLSearchParams(rawInitData);
    const hash = urlParams.get('hash');
    if (!hash) return { isValid: false };

    urlParams.delete('hash');

    const params: string[] = [];
    for (const [key, value] of urlParams.entries()) {
      params.push(`${key}=${value}`);
    }

    params.sort();
    const dataCheckString = params.join('
');

    // Step 1: secret_key = HMAC-SHA256("WebAppData", botToken)
    const secretKey = crypto
      .createHmac('sha256', 'WebAppData')
      .update(botToken)
      .digest();

    // Step 2: calculated_hash = HMAC-SHA256(secret_key, data_check_string)
    const calculatedHash = crypto
      .createHmac('sha256', secretKey)
      .update(dataCheckString)
      .digest('hex');

    if (calculatedHash !== hash) {
      return { isValid: false };
    }

    // Validate authentication timestamp freshness
    const authDateStr = urlParams.get('auth_date');
    if (!authDateStr) return { isValid: false };

    const authDate = parseInt(authDateStr, 10);
    const now = Math.floor(Date.now() / 1000);
    const MAX_AGE_SECONDS = 3600; // 1 hour max replay window

    if (now - authDate > MAX_AGE_SECONDS) {
      return { isValid: false };
    }

    const userJson = urlParams.get('user');
    const user = userJson ? JSON.parse(userJson) : undefined;

    return { isValid: true, user };
  } catch (error) {
    console.error('Validation error:', error);
    return { isValid: false };
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { initData, items } = body as { initData: string; items: ClientItem[] };

    const botToken = process.env.TELEGRAM_BOT_TOKEN;
    if (!botToken) {
      return NextResponse.json({ error: 'Server configuration error' }, { status: 500 });
    }

    if (!initData || !items || !Array.isArray(items) || items.length === 0) {
      return NextResponse.json({ error: 'Invalid request payload' }, { status: 400 });
    }

    // 1. Authenticate context via HMAC validation
    const { isValid, user } = verifyTelegramInitData(initData, botToken);
    if (!isValid) {
      return NextResponse.json({ error: 'Unauthorized payload signature' }, { status: 401 });
    }

    // 2. Server-side price calculation
    let totalAmount = 0;
    const pricesPayload: { label: string; amount: number }[] = [];

    for (const item of items) {
      const product = SERVER_CATALOG[item.id];
      if (!product) {
        return NextResponse.json({ error: `Unknown item ID: ${item.id}` }, { status: 400 });
      }

      if (typeof item.quantity !== 'number' || item.quantity <= 0 || !Number.isInteger(item.quantity)) {
        return NextResponse.json({ error: `Invalid quantity for item: ${item.id}` }, { status: 400 });
      }

      const itemTotal = product.price * item.quantity;
      totalAmount += itemTotal;

      pricesPayload.push({
        label: `${product.title} x${item.quantity}`,
        amount: itemTotal,
      });
    }

    // 3. Request invoice link via Telegram Bot API
    const invoiceResponse = await fetch(`https://api.telegram.org/bot${botToken}/createInvoiceLink`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        title: 'Mini App Order Checkout',
        description: `Order for user ID: ${(user as { id: number })?.id || 'Unknown'}`,
        payload: JSON.stringify({
          userId: (user as { id: number })?.id,
          createdAt: Date.now(),
        }),
        provider_token: process.env.PAYMENT_PROVIDER_TOKEN || '', // Empty for Telegram Stars, or Stripe/Payment provider token
        currency: 'USD',
        prices: pricesPayload,
      }),
    });

    const invoiceData = await invoiceResponse.json();

    if (!invoiceData.ok) {
      console.error('Telegram Bot API Error:', invoiceData);
      return NextResponse.json({ error: invoiceData.description || 'Failed to generate invoice' }, { status: 502 });
    }

    return NextResponse.json({ invoiceLink: invoiceData.result });
  } catch (err) {
    console.error('Checkout API error:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
Enter fullscreen mode Exit fullscreen mode

When configuring payments, passing an empty string to provider_token configures the invoice for Telegram Stars, while passing a live provider token (such as Stripe or Paymentwall) routes transactions through fiat payment processors. The frontend receives invoiceData.result (a https://t.me/$... payment link) and immediately hands execution back to webApp.openInvoice().

Production Considerations: WebViews, Theme Syncing, and Payment Verification

When moving from local testing to production, several platform edge cases must be addressed:

  1. Theme Param Swapping: Users switching their device between Dark Mode and Light Mode on mobile triggers dynamic background updates. If your Next.js application relies on static Tailwind or CSS class names, text contrast will break inside WebViews. Bind color defaults directly to window.Telegram.WebApp.themeParams.bg_color and text_color in root layouts.
  2. Payment Finalization Fallback: The client-side callback inside webApp.openInvoice(url, (status) => ...) executes when the user closes the payment sheet. However, if the Telegram client crashes or network connectivity drops right after payment completion, the browser UI will fail to receive the paid status update. Never fulfill digital goods or update user accounts solely based on the frontend openInvoice status callback.
  3. Webhook Reconciliation: Always listen for incoming successful_payment updates on your backend Telegram webhook server. Treat the webhook payload as the single source of truth for order status updates, and treat client-side SDK callbacks as pure UI state transitions.

If you are shipping production Telegram bots, payments, or complex embedded WebApps, reach out to BotCreator — a studio that specializes in building and scaling custom Telegram tools and automated workflows. You can also consult the official documentation when designing backend Webhook pipeline handlers.

Top comments (0)