### Production Build and Start Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Build the application for production and then start the production server. This is used for deploying the application. ```bash pnpm run build pnpm run start ``` -------------------------------- ### Development Server Output Example Source: https://github.com/telegram-mini-apps/nextjs-template/blob/master/README.md Example output from the Next.js development server indicating the application is running locally. ```bash ▲ Next.js 14.2.3 - Local: http://localhost:3000 ✓ Starting... ✓ Ready in 2.9s ``` -------------------------------- ### HTTPS Development Server Output Example Source: https://github.com/telegram-mini-apps/nextjs-template/blob/master/README.md Example output from the Next.js development server when using HTTPS, showing the secure local link. ```bash ▲ Next.js 14.2.3 - Local: https://localhost:3000 ✓ Starting... ✓ Ready in 2.4s ``` -------------------------------- ### Install Project Dependencies with pnpm Source: https://github.com/telegram-mini-apps/nextjs-template/blob/master/README.md Installs all necessary project dependencies. This template requires pnpm for package management. ```bash pnpm install ``` -------------------------------- ### Run Application in Development Mode Source: https://github.com/telegram-mini-apps/nextjs-template/blob/master/README.md Starts the Next.js development server. This is useful for local testing and development. ```bash pnpm run dev ``` -------------------------------- ### Enable Debug Mode via Start Parameter Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Activate debug mode for the Mini App by setting the 'debug' start parameter. This enables Eruda on mobile devices for easier debugging. You can set this in BotFather or by opening a specific URL. ```bash https://t.me/YourBot/YourApp?startapp=debug ``` -------------------------------- ### Run Application in Development Mode with HTTPS Source: https://github.com/telegram-mini-apps/nextjs-template/blob/master/README.md Starts the Next.js development server using a self-signed SSL certificate, providing an HTTPS link. ```bash pnpm run dev:https ``` -------------------------------- ### Root Component for SSR Guard and Provider Setup Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt The `` component acts as a top-level wrapper, preventing SSR mismatches by rendering a placeholder until client-side hydration. It then sets up the provider tree including `ErrorBoundary`, `TonConnectUIProvider`, and `AppRoot`, configuring appearance and platform based on Telegram context. ```tsx import { Root } from '@/components/Root/Root'; import { I18nProvider } from '@/core/i18n/provider'; // src/app/layout.tsx export default async function RootLayout({ children }: PropsWithChildren) { const locale = await getLocale(); return ( {/* Root handles: SSR guard, ErrorBoundary, TonConnectUIProvider, AppRoot */} {children} ); } // Inside Root — platform-aware AppRoot rendering: // appearance = isDark ? 'dark' : 'light' // platform = ['macos','ios'].includes(tgWebAppPlatform) ? 'ios' : 'base' // // TonConnect manifest must be served at /public/tonconnect-manifest.json: // { "url": "https://your-app.com", "name": "Your App", "iconUrl": "https://your-app.com/logo.png" } ``` -------------------------------- ### Client Instrumentation for Telegram Mini Apps Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt This client-side instrumentation hook initializes the Telegram SDK. It calls `mockEnv` for development, retrieves launch parameters, and configures SDK initialization flags like debug mode, Eruda integration, and macOS mock based on platform and start parameters. ```typescript import { retrieveLaunchParams } from '@tma.js/sdk-react'; import { init } from './core/init'; import { mockEnv } from './mockEnv'; mockEnv().then(() => { try { const launchParams = retrieveLaunchParams(); const { tgWebAppPlatform: platform } = launchParams; // Enable debug via start parameter: t.me/YourBot/app?startapp=debug const debug = (launchParams.tgWebAppStartParam || '').includes('debug') || process.env.NODE_ENV === 'development'; init({ debug, eruda: debug && ['ios', 'android'].includes(platform), // mobile only mockForMacOS: platform === 'macos', }); } catch (e) { console.log(e); } }); ``` -------------------------------- ### Read Init Data with useSignal Hook Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Access raw and parsed Telegram init data (user, receiver, chat objects) using the `useSignal` and `useRawInitData` hooks from `@tma.js/sdk-react`. This example renders the data using `DisplayData` components. ```tsx // src/app/init-data/page.tsx 'use client'; import { initData, useSignal, useRawInitData } from '@tma.js/sdk-react'; import { DisplayData } from '@/components/DisplayData/DisplayData'; import { Page } from '@/components/Page'; import { List, Placeholder } from '@telegram-apps/telegram-ui'; import { useMemo } from 'react'; export default function InitDataPage() { const initDataRaw = useRawInitData(); // raw URLSearchParams string const initDataState = useSignal(initData.state); // parsed object (reactive) const initDataRows = useMemo(() => { if (!initDataState || !initDataRaw) return undefined; return [ { title: 'raw', value: initDataRaw }, ...Object.entries(initDataState).reduce<{ title: string; value: any }[]>( (acc, [title, value]) => { if (value instanceof Date) acc.push({ title, value: value.toISOString() }); else if (!value || typeof value !== 'object') acc.push({ title, value }); return acc; }, [], ), ]; }, [initDataState, initDataRaw]); if (!initDataRows) { return ( ); } return ( {initDataState?.user && ( ({ title, value }))} /> )} ); } // Expected output: Sections listing auth_date, hash, signature, user.id, user.first_name, etc. ``` -------------------------------- ### Initialize SDK and Mount Platform Components Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Initializes the `@tma.js/sdk-react` SDK, mounts platform components, binds CSS variables, optionally loads Eruda, and applies a macOS compatibility patch. Use this function to set up the Telegram Mini App environment. ```typescript // src/core/init.ts import { setDebug, backButton, initData, init as initSDK, miniApp, viewport, mockTelegramEnv, themeParams, retrieveLaunchParams, emitEvent, type ThemeParams, } from '@tma.js/sdk-react'; export async function init(options: { debug: boolean; // enables SDK verbose logging eruda: boolean; // injects Eruda dev console (iOS/Android only) mockForMacOS: boolean; // patches broken macOS Telegram client events }): Promise { setDebug(options.debug); initSDK(); // Eruda mobile inspector — only on debug + mobile platforms if (options.eruda) { const { default: eruda } = await import('eruda'); eruda.init(); eruda.position({ x: window.innerWidth - 50, y: 0 }); } // macOS Telegram client workaround if (options.mockForMacOS) { let firstThemeSent = false; mockTelegramEnv({ onEvent(event, next) { if (event.name === 'web_app_request_theme') { const tp: Partial = firstThemeSent ? (themeParams.state as Partial) : ((firstThemeSent = true), (retrieveLaunchParams().tgWebAppThemeParams || {}) as Partial); return emitEvent('theme_changed', { theme_params: tp as any }); } if (event.name === 'web_app_request_safe_area') { return emitEvent('safe_area_changed', { left: 0, top: 0, right: 0, bottom: 0 }); } next(); }, }); } backButton.mount(); initData.restore(); try { miniApp.mount(); themeParams.bindCssVars(); // exposes --tg-theme-* CSS vars } catch { /* miniApp unavailable outside Telegram */ } try { await viewport.mount(); viewport.bindCssVars(); // exposes --tg-viewport-* CSS vars } catch { /* viewport unavailable outside Telegram */ } } ``` -------------------------------- ### Run a Project Script with pnpm Source: https://github.com/telegram-mini-apps/nextjs-template/blob/master/README.md Executes project scripts such as 'dev', 'build', or 'lint'. Replace '{script}' with the desired script name. ```bash pnpm run {script} # Example: pnpm run build ``` -------------------------------- ### Display Launch Parameters with useLaunchParams Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Retrieve and display current Telegram launch parameters using the `useLaunchParams` hook. The `DisplayData` component is used to list parameters like platform, version, and bot inline status. ```tsx // src/app/launch-params/page.tsx 'use client'; import { useLaunchParams } from '@tma.js/sdk-react'; import { DisplayData } from '@/components/DisplayData/DisplayData'; import { List } from '@telegram-apps/telegram-ui'; import { Page } from '@/components/Page'; export default function LaunchParamsPage() { const lp = useLaunchParams(); return ( ); } ``` -------------------------------- ### Linting the Project Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Run the linter to check for code style and potential errors. This command helps maintain code quality. ```bash pnpm run lint ``` -------------------------------- ### Simulate Development Environment with mockEnv Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt This function simulates the Telegram Mini App environment for development purposes. It intercepts platform events and provides fake launch parameters when not running in a real Telegram context. The mock is removed in production builds. ```typescript import { mockTelegramEnv, isTMA, emitEvent } from '@tma.js/sdk-react'; export async function mockEnv(): Promise { if (process.env.NODE_ENV !== 'development') return; const isTma = await isTMA('complete'); if (isTma) return; // already inside Telegram — do nothing const themeParams = { accent_text_color: '#6ab2f2', bg_color: '#17212b', button_color: '#5288c1', button_text_color: '#ffffff', destructive_text_color: '#ec3942', header_bg_color: '#17212b', hint_color: '#708499', link_color: '#6ab3f3', secondary_bg_color: '#232e3c', section_bg_color: '#17212b', section_header_text_color: '#6ab3f3', subtitle_text_color: '#708499', text_color: '#f5f5f5', } as const; const noInsets = { left: 0, top: 0, bottom: 0, right: 0 } as const; mockTelegramEnv({ onEvent(e, next) { if (e.name === 'web_app_request_theme') return emitEvent('theme_changed', { theme_params: themeParams as any }); if (e.name === 'web_app_request_viewport') return emitEvent('viewport_changed', { height: window.innerHeight, width: window.innerWidth, is_expanded: true, is_state_stable: true, }); if (e.name === 'web_app_request_content_safe_area') return emitEvent('content_safe_area_changed', noInsets); if (e.name === 'web_app_request_safe_area') return emitEvent('safe_area_changed', noInsets); next(); }, launchParams: new URLSearchParams([ ['tgWebAppThemeParams', JSON.stringify(themeParams)], ['tgWebAppData', new URLSearchParams([ ['auth_date', String(Date.now() / 1000 | 0)], ['hash', 'some-hash'], ['signature', 'some-signature'], ['user', JSON.stringify({ id: 1, first_name: 'Vladislav' })], ]).toString()], ['tgWebAppVersion', '8.4'], ['tgWebAppPlatform', 'tdesktop'], ]), }); } ``` -------------------------------- ### Internal/External Link Navigation with `` Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Wraps Next.js `` for unified internal and external navigation. For same-origin URLs, it uses Next.js client-side navigation. For external URLs, it utilizes `openLink()` from the Telegram SDK to open links within the Telegram in-app browser. ```tsx import { Link } from '@/components/Link/Link'; // Internal — standard Next.js client navigation View Init Data // External — automatically intercepted and opened via openLink() TON Website // With UrlObject Theme ``` -------------------------------- ### DisplayData Component for Key-Value Pairs Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt A reusable component to render structured key-value data. It automatically formats RGB hex strings as color swatches and boolean values as checkboxes. Use this for displaying user info, settings, or any structured data. ```tsx // src/components/DisplayData/DisplayData.tsx import { DisplayData, type DisplayDataRow } from '@/components/DisplayData/DisplayData'; const rows: DisplayDataRow[] = [ { title: 'name', value: 'Vladislav' }, { title: 'verified', value: true }, // → disabled Checkbox ✓ { title: 'bg_color', value: '#17212b' }, // → RGB swatch + hex text { title: 'profile', type: 'link', value: '/init-data' }, // → "Open" link { title: 'missing', value: undefined }, // → empty ]; // Renders a Section with a Cell per row; subhead = title, content = value node ``` -------------------------------- ### Server Actions for Locale Persistence: `getLocale` / `setLocale` Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Server actions to manage the `NEXT_LOCALE` cookie for persisting user locale preferences. `setLocale` is automatically invoked by the `Root` component when `initData.user.language_code` changes, synchronizing the app's locale with the user's Telegram language setting. Translations are managed in JSON files under the `public/locales` directory. ```typescript // src/core/i18n/locale.ts (server actions) import { getLocale, setLocale } from '@/core/i18n/locale'; // Reading locale on the server (e.g., in layout.tsx) const locale = await getLocale(); // → 'en' | 'ru' | defaultLocale fallback // Setting locale (called from Root useEffect or LocaleSwitcher) await setLocale('ru'); // writes NEXT_LOCALE=ru cookie // Adding translations — public/locales/en.json: { "i18n": { "header": "Application supports i18n", "footer": "You can select a different language from the dropdown menu." } } // Consuming in a component: import { useTranslations } from 'next-intl'; const t = useTranslations('i18n');
``` -------------------------------- ### Reactively Read Telegram Theme Parameters Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Reads the Telegram color palette reactively from themeParams.state or falls back to launch parameters. Use this to dynamically adjust your app's theme. ```tsx // src/app/theme-params/page.tsx 'use client'; import { themeParams, useSignal, useLaunchParams } from '@tma.js/sdk-react'; import { useMemo } from 'react'; import { DisplayData } from '@/components/DisplayData/DisplayData'; export default function ThemeParamsPage() { const tp = useSignal(themeParams.state); const lp = useLaunchParams(); const rows = useMemo(() => { const data = (Object.keys(tp || {}).length > 0 ? tp : lp.tgWebAppThemeParams) || {}; return Object.entries(data).map(([title, value]) => ({ // normalize camelCase → snake_case and "background" → "bg" title: title.replace(/[A-Z]/g, (m) => `_${m.toLowerCase()}`).replace(/background/, 'bg'), value, })); }, [tp, lp.tgWebAppThemeParams]); // Expected rows: bg_color, button_color, hint_color, link_color, text_color, ... return ; } ``` -------------------------------- ### Control Back Button Visibility with Page Wrapper Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Use the `` component to manage the visibility of Telegram's native back button. Set `back={false}` on root pages to hide it; it's shown by default on sub-pages. ```tsx // src/components/Page.tsx import { Page } from '@/components/Page'; // Root page — hide the back button export default function Home() { return ( {/* content */} ); } // Sub-page — show back button (default) export default function SettingsPage() { return ( {/* Telegram back button appears automatically; tapping it calls router.back() */} ); } ``` -------------------------------- ### TON Connect Wallet Integration Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Integrates TON Connect for wallet functionality. Displays a connect button if no wallet is linked, otherwise shows account and device information. Uses openLink to open wallet URLs in the in-app browser. ```tsx // src/app/ton-connect/page.tsx 'use client'; import { openLink } from '@tma.js/sdk-react'; import { TonConnectButton, useTonWallet } from '@tonconnect/ui-react'; import { Avatar, Cell, List, Section, Title, Navigation } from '@telegram-apps/telegram-ui'; import { DisplayData } from '@/components/DisplayData/DisplayData'; import { Page } from '@/components/Page'; export default function TONConnectPage() { const wallet = useTonWallet(); // null until user taps TonConnectButton if (!wallet) { return ( {/* Renders the official TON Connect modal button */} ); } const { account: { chain, publicKey, address }, device: { appName, appVersion, platform, features } } = wallet; return ( {'imageUrl' in wallet && (
} after={About wallet} subtitle={wallet.appName} onClick={(e) => { e.preventDefault(); openLink(wallet.aboutUrl); }} > {wallet.name}
)} typeof f === 'object' ? f.name : undefined).filter(Boolean).join(', ') }, ]} />
); } // Required: /public/tonconnect-manifest.json // { "url": "https://your-app.com", "name": "Your App", "iconUrl": "https://your-app.com/logo.png" } ``` -------------------------------- ### Runtime Locale Selector `` Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt A Telegram UI ` with English / Русский options. // Selecting an option calls setLocale(value) which sets the NEXT_LOCALE cookie. // Adding a new locale: // 1. Add key to locales array in config.ts // 2. Add entry to localesMap // 3. Create public/locales/.json with your translation keys ``` -------------------------------- ### Conditional Class Name Joiner: `classNames(...values)` Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt A utility function for joining CSS class names, similar to the popular `classnames` npm package. It supports various input types including strings, objects with boolean conditions, and arrays, allowing for dynamic class name generation. ```typescript // src/css/classnames.ts import { classNames } from '@/css/classnames'; classNames('foo', 'bar') // → 'foo bar' classNames('foo', { bar: true, baz: false }) // → 'foo bar' classNames(['foo', null, 'bar']) // → 'foo bar' classNames('base', isActive && 'active') // → 'base active' or 'base' classNames(undefined, '', 'valid') // → 'valid' ``` -------------------------------- ### RGB Color Swatch Component `` Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt Renders a small colored square followed by its hex string representation. This component is automatically used by `DisplayData` when an RGB value is detected. It checks for valid RGB hex strings using the regex /^#[0-9A-Fa-f]{6}$/. ```tsx import { RGB } from '@/components/RGB/RGB'; // Renders: [■] #5288c1 (■ is a filled square with backgroundColor: #5288c1) // Used internally by DisplayData when isRGB(value) === true // isRGB checks: /^#[0-9A-Fa-f]{6}$/ ``` -------------------------------- ### BEM Class Name Factory: `bem(block)` Source: https://context7.com/telegram-mini-apps/nextjs-template/llms.txt A utility function that generates BEM (Block, Element, Modifier) class names. It returns a tuple containing a block function and an element function. The block function creates base block classes with optional modifiers, while the element function generates `block__element` classes with optional modifiers. ```typescript // src/css/bem.ts import { bem } from '@/css/bem'; const [b, e] = bem('my-card'); b() // → 'my-card' b('active') // → 'my-card my-card--active' b({ active: true, big: false }) // → 'my-card my-card--active' e('header') // → 'my-card__header' e('header', 'large') // → 'my-card__header my-card__header--large' e('icon', { hidden: true }) // → 'my-card__icon my-card__icon--hidden' // Real usage in ton-connect/page.tsx: const [, e] = bem('ton-connect-page'); // → className="ton-connect-page__button" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.