### Example Direct Link with Start Parameter Source: https://docs.telegram-mini-apps.com/platform/start-parameter This is an example of a direct link to a Mini App that includes the `startapp` query parameter, which will set the start parameter. ```url https://t.me/botusername/appname?startapp=ABC ``` -------------------------------- ### Example Bot Link with Start Parameter Source: https://docs.telegram-mini-apps.com/platform/start-parameter This is an example of a bot link that includes the `startattach` query parameter, which will set the start parameter for the Mini App. ```url https://t.me/botusername?startattach=ABC ``` -------------------------------- ### Installation Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-react Install the @tma.js/sdk-react package. It is recommended to have React installed as it is a peer dependency. ```APIDOC pnpm i @tma.js/sdk-react npm i @tma.js/sdk-react yarn add @tma.js/sdk-react ``` -------------------------------- ### Install @tma.js/init-data-node with yarn Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node Install the package using yarn. ```bash yarn add @tma.js/init-data-node ``` -------------------------------- ### Install @tma.js/init-data-node with npm Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node Install the package using npm. ```bash npm i @tma.js/init-data-node ``` -------------------------------- ### Mock Telegram Environment Example Source: https://docs.telegram-mini-apps.com/packages/tma-js-bridge/environment This snippet shows how to initialize a mocked Telegram environment. It includes setting up launch parameters like theme, user data, and start parameters, as well as defining event handlers for theme, viewport, and safe area changes. Use this for local development and testing without a live Telegram connection. ```typescript import { mockTelegramEnv, emitEvent } from '@tma.js/bridge'; const noInsets = { left: 0, top: 0, bottom: 0, right: 0, } as const; 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; mockTelegramEnv({ launchParams: { tgWebAppThemeParams: themeParams, tgWebAppData: new URLSearchParams([ ['user', JSON.stringify({ id: 1, first_name: 'Pavel', })], ['hash', ''], ['signature', ''], ['auth_date', Date.now().toString()], ]), tgWebAppStartParam: 'debug', tgWebAppVersion: '8', tgWebAppPlatform: 'tdesktop', }, onEvent(event) { // event here is an object { event: string; params?: any }, but // typed depending on the "event" prop. if (event.name === 'web_app_request_theme') { return emitEvent('theme_changed', { theme_params: themeParams }); } if (event.name === 'web_app_request_viewport') { return emitEvent('viewport_changed', { height: window.innerHeight, width: window.innerWidth, is_expanded: true, is_state_stable: true, }); } if (event.name === 'web_app_request_content_safe_area') { return emitEvent('content_safe_area_changed', noInsets); } if (event.name === 'web_app_request_safe_area') { return emitEvent('safe_area_changed', noInsets); } }, }); ``` -------------------------------- ### Install @tma.js/init-data-node with pnpm Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node Install the package using pnpm. ```bash pnpm i @tma.js/init-data-node ``` -------------------------------- ### Complete signing example for Node.js Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node/signing A comprehensive example demonstrating how to use the `sign` method in a Node.js environment with all necessary parameters. ```typescript import { sign } from '@tma.js/init-data-node'; sign( { can_send_after: 10000, chat: { id: 1, type: 'group', username: 'my-chat', title: 'chat-title', photo_url: 'chat-photo', }, chat_instance: '888', chat_type: 'sender', query_id: 'QUERY', receiver: { added_to_attachment_menu: false, allows_write_to_pm: true, first_name: 'receiver-first-name', id: 991, is_bot: false, is_premium: true, language_code: 'ru', last_name: 'receiver-last-name', photo_url: 'receiver-photo', username: 'receiver-username', }, start_param: 'debug', user: { added_to_attachment_menu: false, allows_write_to_pm: false, first_name: 'user-first-name', id: 222, is_bot: true, is_premium: false, language_code: 'en', last_name: 'user-last-name', photo_url: 'user-photo', username: 'user-username', }, }, '5768337691:AAH5YkoiEuPk8-FZa32hStHTqXiLPtAEhx8', new Date(1000), ); ``` -------------------------------- ### Install @tma.js/sdk-vue with npm Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-vue Install the package using npm. Assumes Vue is already installed. ```bash npm i @tma.js/sdk-vue ``` -------------------------------- ### Install @tma.js/sdk-vue with pnpm Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-vue Install the package using pnpm. Assumes Vue is already installed. ```bash pnpm i @tma.js/sdk-vue ``` -------------------------------- ### Get Start Param Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the value of the `startattach` or `startapp` query parameter from the launch link. Returns a string or `undefined`. ```typescript initData.startParam(); // 'my-value' ``` -------------------------------- ### Basic Usage Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-react A simple example demonstrating how to initialize the SDK and mount the Back Button component. ```APIDOC import ReactDOM from 'react-dom/client'; import { init, backButton } from '@tma.js/sdk-react'; import { BackButton } from './BackButton.js'; // Initialize the package. init(); // Mount the Back Button, so we will work with // the actual component properties. backButton.mount(); ReactDOM .createRoot(document.getElementById('root')!) .render(); ``` -------------------------------- ### Install @tma.js/sdk-vue with yarn Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-vue Install the package using yarn. Assumes Vue is already installed. ```bash yarn add @tma.js/sdk-vue ``` -------------------------------- ### Install @tma.js/sdk-solid Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-solid Install the SDK package using your preferred package manager. ```bash pnpm i @tma.js/sdk-solid ``` ```bash npm i @tma.js/sdk-solid ``` ```bash yarn add @tma.js/sdk-solid ``` -------------------------------- ### Install @tma.js/signals with yarn Source: https://docs.telegram-mini-apps.com/packages/tma-js-signals Install the signals package using yarn. ```bash yarn add @tma.js/signals ``` -------------------------------- ### Install @tma.js/signals with npm Source: https://docs.telegram-mini-apps.com/packages/tma-js-signals Install the signals package using npm. ```bash npm i @tma.js/signals ``` -------------------------------- ### Install @tma.js/sdk-svelte with npm Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-svelte Install the package using npm. Assumes svelte-js is already installed. ```bash npm i @tma.js/sdk-svelte ``` -------------------------------- ### Install @tma.js/sdk-react Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-react Install the SDK React package using your preferred package manager. ```bash pnpm i @tma.js/sdk-react ``` ```bash npm i @tma.js/sdk-react ``` ```bash yarn add @tma.js/sdk-react ``` -------------------------------- ### Install @tma.js/sdk-svelte with yarn Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-svelte Install the package using yarn. Assumes svelte-js is already installed. ```bash yarn add @tma.js/sdk-svelte ``` -------------------------------- ### Complete signing example for Web Crypto API Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node/signing An example of using the `sign` method in a browser environment with the Web Crypto API. Note the use of `await` as the operation is asynchronous. ```typescript import { sign } from '@tma.js/init-data-node/web'; await sign( { can_send_after: 10000, chat: { id: 1, type: 'group', username: 'my-chat', title: 'chat-title', photo_url: 'chat-photo', }, chat_instance: '888', chat_type: 'sender', query_id: 'QUERY', receiver: { added_to_attachment_menu: false, allows_write_to_pm: true, first_name: 'receiver-first-name', id: 991, is_bot: false, is_premium: true, language_code: 'ru', last_name: 'receiver-last-name', photo_url: 'receiver-photo', username: 'receiver-username', }, start_param: 'debug', user: { added_to_attachment_menu: false, allows_write_to_pm: false, first_name: 'user-first-name', id: 222, is_bot: true, is_premium: false, language_code: 'en', last_name: 'user-last-name', photo_url: 'user-photo', username: 'user-username', }, }, '5768337691:AAH5YkoiEuPk8-FZa32hStHTqXiLPtAEhx8', new Date(1000), ); ``` -------------------------------- ### Install Core Telegram Mini Apps SDK (npm) Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/usage-tips Install the core SDK package using npm when not using a framework-specific wrapper. ```bash npm i @tma.js/sdk ``` -------------------------------- ### Install Telegram Mini Apps SDK (npm) Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/usage-tips Use this command to install the core SDK package with npm if your project does not rely on a specific framework wrapper. ```bash npm i @tma.js/sdk-react ``` -------------------------------- ### Install @tma.js/sdk-svelte with pnpm Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-svelte Install the package using pnpm. Assumes svelte-js is already installed. ```bash pnpm i @tma.js/sdk-svelte ``` -------------------------------- ### Install @tma.js/signals with pnpm Source: https://docs.telegram-mini-apps.com/packages/tma-js-signals Install the signals package using pnpm. ```bash pnpm i @tma.js/signals ``` -------------------------------- ### Install Core Telegram Mini Apps SDK (yarn) Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/usage-tips Install the core SDK package using yarn when not using a framework-specific wrapper. ```bash yarn add @tma.js/sdk ``` -------------------------------- ### Install Telegram Mini Apps SDK (yarn) Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/usage-tips Use this command to install the core SDK package with yarn if your project does not rely on a specific framework wrapper. ```bash yarn add @tma.js/sdk-react ``` -------------------------------- ### Initialize SDK and Mount Back Button Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-solid Initialize the SDK and mount the Back Button component. This setup is necessary to interact with the actual component properties. ```tsx import { render } from 'solid-js/web'; import { init, backButton } from '@tma.js/sdk-solid'; import { BackButton } from './BackButton.js'; // Initialize the package. init(); // Mount the Back Button, so we will work with // the actual component properties. backButton.mount(); render(() => , document.getElementById('root')!); ``` -------------------------------- ### Install Telegram Mini Apps SDK (pnpm) Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/usage-tips Use this command to install the core SDK package with pnpm if your project does not rely on a specific framework wrapper. ```bash pnpm i @tma.js/sdk-react ``` -------------------------------- ### Install Core Telegram Mini Apps SDK (pnpm) Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/usage-tips Install the core SDK package using pnpm when not using a framework-specific wrapper. ```bash pnpm i @tma.js/sdk ``` -------------------------------- ### Install @tma.js/bridge with npm Source: https://docs.telegram-mini-apps.com/packages/tma-js-bridge Install the @tma.js/bridge package using npm. ```bash npm i @tma.js/bridge ``` -------------------------------- ### Install @tma.js/bridge with yarn Source: https://docs.telegram-mini-apps.com/packages/tma-js-bridge Install the @tma.js/bridge package using yarn. ```bash yarn add @tma.js/bridge ``` -------------------------------- ### Install @tma.js/bridge with pnpm Source: https://docs.telegram-mini-apps.com/packages/tma-js-bridge Install the @tma.js/bridge package using pnpm. ```bash pnpm i @tma.js/bridge ``` -------------------------------- ### Example Init Data for Third-Party Validation Source: https://docs.telegram-mini-apps.com/platform/init-data Sample init data string including URL-encoded parameters, auth date, hash, and signature, used for third-party validation. ```text user=%7B%22id%22%3A279058397%2C%22first_name%22%3A%22Vladislav%20%2B%20-%20%3F%20%5C%2F%22%2C%22last_name%22%3A%22Kibenko%22%2C%22username%22%3A%22vdkfrost%22%2C%22language_code%22%3A%22ru%22%2C%22is_premium%22%3Atrue%2C%22allows_write_to_pm%22%3Atrue%2C%22photo_url%22%3A%22https%3A%5C%2F%5C%2Ft.me%5C%2Fi%5C%2Fuserpic%5C%2F320%5C%2F4FPEE4tmP3ATHa57u6MqTDih13LTOiMoKoLDRG4PnSA.svg%22%7D&chat_instance=8134722200314281151&chat_type=private&auth_date=1733584787&hash=2174df5b000556d044f3f020384e879c8efcab55ddea2ced4eb752e93e7080d6&signature=zL-ucjNyREiHDE8aihFwpfR9aggP2xiAo3NSpfe-p7IbCisNlDKlo7Kb6G4D0Ao2mBrSgEk4maLSdv6MLIlADQ ``` -------------------------------- ### Example Raw Init Data for Validation Source: https://docs.telegram-mini-apps.com/platform/init-data This is the raw initialization data string received from the Mini App. It includes various parameters and a signature hash, used for server-side validation. ```text query_id=AAHdF6IQAAAAAN0XohDhrOrc&user=%7B%22id%22%3A279058397%2C%22first_name%22%3A%22Vladislav%22%2C%22last_name%22%3A%22Kibenko%22%2C%22username%22%3A%22vdkfrost%22%2C%22language_code%22%3A%22ru%22%2C%22is_premium%22%3Atrue%7D&auth_date=1662771648&hash=c501b71e775f74ce10e377dea85a7ea24ecd640b223ea86dfe453e0eaed2e2b2 ``` -------------------------------- ### Install Localtunnel Source: https://docs.telegram-mini-apps.com/platform/getting-app-link Install the localtunnel package globally using npm. This tool provides a free alternative to ngrok for creating tunnels to your local development server. ```bash npm install -g localtunnel ``` -------------------------------- ### Functional signing example for Node.js Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node/signing Demonstrates signing init data using a functional programming approach with `signFp` and `fp-ts/Either` for error handling in Node.js. ```typescript import { signFp } from '@tma.js/init-data-node'; import * as E from 'fp-ts/Either'; import { pipe } from 'fp-ts/function'; pipe( signFp( { can_send_after: 10000, chat: { id: 1, type: 'group', username: 'my-chat', title: 'chat-title', photo_url: 'chat-photo', }, chat_instance: '888', chat_type: 'sender', query_id: 'QUERY', receiver: { added_to_attachment_menu: false, allows_write_to_pm: true, first_name: 'receiver-first-name', id: 991, is_bot: false, is_premium: true, language_code: 'ru', last_name: 'receiver-last-name', photo_url: 'receiver-photo', username: 'receiver-username', }, start_param: 'debug', user: { added_to_attachment_menu: false, allows_write_to_pm: false, first_name: 'user-first-name', id: 222, is_bot: true, is_premium: false, language_code: 'en', last_name: 'user-last-name', photo_url: 'user-photo', username: 'user-username', }, }, '5768337691:AAH5YkoiEuPk8-FZa32hStHTqXiLPtAEhx8', new Date(1000), ), E.match( error => { // Something went wrong. }, signedData => { // Signing is successful. }, ), ); ``` -------------------------------- ### Web Crypto API Functional Signing Example Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node/signing An example using the functional `signFp` for browser environments, leveraging `fp-ts/TaskEither` for asynchronous error handling. ```typescript import { signFp } from '@tma.js/init-data-node/web'; import * as TE from 'fp-ts/TaskEither'; import { pipe } from 'fp-ts/function'; pipe( signFp( { can_send_after: 10000, chat: { id: 1, type: 'group', username: 'my-chat', title: 'chat-title', photo_url: 'chat-photo', }, chat_instance: '888', chat_type: 'sender', query_id: 'QUERY', receiver: { added_to_attachment_menu: false, allows_write_to_pm: true, first_name: 'receiver-first-name', id: 991, is_bot: false, is_premium: true, language_code: 'ru', last_name: 'receiver-last-name', photo_url: 'receiver-photo', username: 'receiver-username', }, }, '5768337691:AAH5YkoiEuPk8-FZa32hStHTqXiLPtAEhx8', new Date(1000), ), TE.match( error => { // Something went wrong. }, signedData => { // Signing is successful. }, ), ); ``` -------------------------------- ### web_app_start_gyroscope Source: https://docs.telegram-mini-apps.com/platform/methods Starts tracking gyroscope data. Available since v8.0. ```APIDOC ## web_app_start_gyroscope ### Description Starts tracking gyroscope data. ### Parameters #### Query Parameters - **refresh_rate** (number) - Optional - The refresh rate in milliseconds, with acceptable values ranging from 20 to 1000. Note that `refresh_rate` may not be supported on all platforms, so the actual tracking frequency may differ from the specified value. ``` -------------------------------- ### Example of Signed Initialization Data String Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node/signing This string represents the format of the signed initialization data, including all relevant user and chat information, along with the computed hash. ```plaintext 'auth_date=1' + '&can_send_after=10000' + '&chat=%7B%22id%22%3A1%2C%22type%22%3A%22group%22%2C%22title%22%3A%22chat-title%22%2C%22photo_url%22%3A%22group%22%2C%22username%22%3A%22my-chat%22%7D' + '&chat_instance=888' + '&chat_type=sender' + '&query_id=QUERY' + '&receiver=%7B%22added_to_attachment_menu%22%3Afalse%2C%22allows_write_to_pm%22%3Atrue%2C%22first_name%22%3A%22receiver-first-name%22%2C%22id%22%3A991%2C%22is_bot%22%3Afalse%2C%22is_premium%22%3Atrue%2C%22language_code%22%3A%22ru%22%2C%22last_name%22%3A%22receiver-last-name%22%2C%22photo_url%22%3A%22receiver-photo%22%2C%22username%22%3A%22receiver-username%22%7D' + '&start_param=debug' + '&user=%7B%22added_to_attachment_menu%22%3Afalse%2C%22allows_write_to_pm%22%3Afalse%2C%22first_name%22%3A%22user-first-name%22%2C%22id%22%3A222%2C%22is_bot%22%3Atrue%2C%22is_premium%22%3Afalse%2C%22language_code%22%3A%22en%22%2C%22last_name%22%3A%22user-last-name%22%2C%22photo_url%22%3A%22user-photo%22%2C%22username%22%3A%22user-username%22%7D' + '&hash=47cfa22e72b887cba90c9cb833c5ea0f599975b6ce7193741844b5c4a4228b40' ``` -------------------------------- ### Example Telegram Theme Parameters Source: https://docs.telegram-mini-apps.com/platform/theming This JSON object shows the structure and example values for theme parameters provided by Telegram. Use these to match your app's appearance to the Telegram client. ```json { "accent_text_color": "#6ab2f2", "bg_color": "#17212b", "button_color": "#5288c1", "button_text_color": "#ffffff", "bottom_bar_bg_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" } ``` -------------------------------- ### web_app_add_to_home_screen Source: https://docs.telegram-mini-apps.com/platform/methods Prompts the user to add the Mini App to their home screen. Note that the event may not be received if the device cannot determine the installation status. ```APIDOC ## web_app_add_to_home_screen ### Description Prompts the user to add the Mini App to the home screen. Note that if the device cannot determine the installation status, the event may not be received even if the icon has been added. ### Available since v8.0 ``` -------------------------------- ### Get Raw Launch Parameters with useRawLaunchParams Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-react Retrieve launch parameters in their raw, URL-encoded string format using the `useRawLaunchParams` hook. ```ts import { useRawLaunchParams } from '@tma.js/sdk-react'; function Component() { console.log(useRawLaunchParams()); // tgWebAppBotInline=0&tgWebAppData=%7B%22user%22%3A%7B%7D... } ``` -------------------------------- ### Using useSignal Hook Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-solid Demonstrates how to use the `useSignal` helper to integrate SDK signals with Solid.js signals. This example shows how to track the back button's visibility. ```ts import { createEffect, onCleanup, onMount } from 'solid-js'; import { backButton, useSignal } from '@tma.js/sdk-solid'; function Component() { const isVisible = useSignal(backButton.isVisible); createEffect(() => { console.log('The button is', isVisible() ? 'visible' : 'invisible'); }); onMount(() => { backButton.show(); onCleanup(() => { backButton.hide(); }); }); return null; } ``` -------------------------------- ### Event: `accelerometer_started` Source: https://docs.telegram-mini-apps.com/platform/events This event signifies that the accelerometer data tracking has been successfully started. ```APIDOC ## `accelerometer_started` Event ### Description Fired when the accelerometer data tracking has been successfully initiated. Available since version 8.0. ``` -------------------------------- ### Functional signing example for Web Crypto API Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node/signing Demonstrates signing init data using `signFp` with `fp-ts/TaskEither` for asynchronous error handling in browser environments. ```typescript import { signFp } from '@tma.js/init-data-node/web'; import * as TE from 'fp-ts/TaskEither'; import { pipe } from 'fp-ts/function'; pipe( signFp( { can_send_after: 10000, chat: { id: 1, type: 'group', username: 'my-chat', title: 'chat-title', photo_url: 'chat-photo', }, chat_instance: '888', chat_type: 'sender', query_id: 'QUERY', receiver: { ``` -------------------------------- ### web_app_start_accelerometer Source: https://docs.telegram-mini-apps.com/platform/methods Starts tracking accelerometer data. This method is useful for games and applications that require motion input. ```APIDOC ## web_app_start_accelerometer ### Description Starts tracking accelerometer data. ### Parameters #### Request Body - **refresh_rate** (number) - Required - The refresh rate in milliseconds, with acceptable values ranging from 20 to 1000. Note that `refresh_rate` may not be supported on all platforms, so the actual tracking frequency may differ from the specified value. ``` -------------------------------- ### Get VK Launch Parameters Source: https://docs.telegram-mini-apps.com/platform/migrating-from-vk On the frontend, use the `vk-bridge` library to send the `VKWebAppGetLaunchParams` event. This retrieves the `sign` and other `signParams` necessary for backend validation. ```typescript const { sign, ...signParams } = await bridge.send('VKWebAppGetLaunchParams'); ``` -------------------------------- ### web_app_start_device_orientation Source: https://docs.telegram-mini-apps.com/platform/methods Starts tracking device orientation data. This method provides data about the device's orientation, which can be used for various interactive features. ```APIDOC ## web_app_start_device_orientation ### Description Starts tracking device orientation data. ### Parameters #### Request Body - **refresh_rate** (number) - Required - The refresh rate in milliseconds, with acceptable values ranging from 20 to 1000. Note that `refresh_rate` may not be supported on all platforms, so the actual tracking frequency may differ from the specified value. - **need_absolute** (boolean) - Optional - Pass true to receive absolute orientation data, allowing you to determine the device's attitude relative to magnetic north. Use this option if implementing features like a compass in your app. If relative data is sufficient, pass false. Keep in mind that some devices may not support absolute orientation data. In such cases, you will receive relative data even if need_absolute=true is passed. ``` -------------------------------- ### viewport_changed Source: https://docs.telegram-mini-apps.com/platform/events This event is triggered whenever the viewport has been changed, for example, when the user starts dragging the application or calls the expansion method. ```APIDOC ## viewport_changed ### Description Occurs whenever the viewport has been changed. For example, when the user started dragging the application or called the expansion method. ### Fields - **height** (number) - The viewport height. - **width** (number) - Optional - The viewport width. - **is_expanded** (boolean) - Is the viewport currently expanded. - **is_state_stable** (boolean) - Is the viewport current state stable and not going to change in the next moment. ### Tip Pay attention to the fact that the send rate of this method is not enough to smoothly resize the application window. You should probably use a stable height instead of the current one, or handle this problem in another way. ``` -------------------------------- ### Ready Method Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/mini-app The `ready` method signals that the Mini App is ready to be displayed, hiding the loading placeholder and showing the Mini App. It should be called as early as possible for a smooth user experience. ```APIDOC ## `ready` To signal that the Mini App is ready to be displayed, use the `ready` method. Once called, the loading placeholder is hidden, and the Mini App is shown. ```ts miniApp.ready(); ``` TIP Call this function as early as possible after loading essential interface elements to ensure a smooth user experience. ``` -------------------------------- ### Initialize SDK and use BackButton component in Svelte Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-svelte Basic Svelte component setup to initialize the SDK and render a BackButton. Ensure the BackButton component is imported and used. ```svelte ``` -------------------------------- ### Retrieve Raw Launch Parameters - TypeScript Source: https://docs.telegram-mini-apps.com/packages/tma-js-bridge/launch-parameters To get launch parameters in their initial format as query parameters, use this function. The output is a string of key-value pairs. ```typescript import { retrieveRawLaunchParams } from '@tma.js/bridge'; retrieveRawLaunchParams(); // tgWebAppBotInline=0&tgWebAppData=%7B%22user%22%3A%7B%7D%2C%22auth_date%22%3A1787367222%2C%22query_id%22%3A%22abc%22%7D...&... ``` -------------------------------- ### Call Method using @tma.js/sdk Source: https://docs.telegram-mini-apps.com/platform/methods Simplify method calls across different platforms using the @tma.js/sdk package. This example shows how to set the header color. ```typescript import { postEvent } from '@tma.js/sdk'; postEvent('web_app_set_header_color', { color_key: 'bg_color' }); ``` -------------------------------- ### Track Home Screen Addition Status Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/home-screen Listen for events related to adding the Mini App to the home screen. Use `on` to subscribe and `off` to unsubscribe. Note that events may not be received if the device cannot determine the installation status. ```typescript import { on, off } from '@tma.js/sdk'; function onAdded() { console.log('Added'); } on('home_screen_added', onAdded); off('home_screen_added', onAdded); function onFailed() { console.log('User declined the request'); } on('home_screen_failed', onFailed); off('home_screen_failed', onFailed); ``` -------------------------------- ### Initialize SDK with Updated Options Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/migrate-from-telegram-apps The `init` function options have been updated. You no longer need to pass a complete set of launch parameters. ```typescript interface InitOptions { /** * True if SDK should accept styles sent from the Telegram * application. * @default true */ acceptCustomStyles?: boolean; /** * True if the application is launched in inline mode. * @default Will be calculated based on the launch parameters' * tgWebAppBotInline field. */ isInlineMode?: boolean; /** * A custom `postEvent` function to use across the package. * @default tma.js/bridge's postEventFp function will be used. */ postEvent?: PostEventFpFn; /** * Mini application theme parameters. * @default Will be calculated based on the launch parameters' * tgWebAppThemeParams field. */ themeParams?: ThemeParams; /** * Telegram Mini Apps version supported by the Telegram * client. * @default Will be calculated based on the launch parameters' * tgWebAppVersion field. */ version?: Version; } ``` -------------------------------- ### Initialize SDK with `initFp` Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/initializing Use the `initFp` function for initialization. This is an alternative to `init` and also configures the SDK's global dependencies. ```typescript import { initFp } from '@tma.js/sdk'; initFp(); ``` -------------------------------- ### Validate Init Data with Hashed Token Source: https://docs.telegram-mini-apps.com/packages/tma-js-init-data-node/validating This example demonstrates how to use the `validate` function with a hashed secret token. This approach is useful for reducing the instances where you directly pass a raw token. ```APIDOC ## validate ### Description Validates Telegram Mini App init data. It can optionally use a hashed secret token for enhanced security. ### Method `validate(initData: string, secretToken: string, options?: { tokenHashed: true })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts import { validate } from '@tma.js/init-data-node'; validate( // Init data. 'query_id=AAHdF6IQAAAAAN0XohDhrOrc' + '&user=%7B%22id%22%3A279058397%2C%22first_name%22%3A%22Vladislav%22%2C%22last_name%22%3A%22Kibenko%22%2C%22username%22%3A%22vdkfrost%22%2C%22language_code%22%3A%22ru%22%2C%22is_premium%22%3Atrue%7D' + '&auth_date=1662771648' + '&hash=c501b71e775f74ce10e377dea85a7ea24ecd640b223ea86dfe453e0eaed2e2b2', // Hashed secret token. 'a5c609aa52f63cb5e6d8ceb6e4138726ea82bbc36bb786d64482d445ea38ee5f', { tokenHashed: true }, ); ``` ### Response #### Success Response (void) Returns void if the init data is valid. #### Error Response Throws an error if the init data is invalid. #### Response Example None ``` -------------------------------- ### Get Can Send After Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Get the number of seconds after which a message can be sent using `answerWebAppQuery`. Returns a number or `undefined`. ```typescript initData.canSendAfter(); // 3600 ``` -------------------------------- ### Initialize SDK and handle Back Button Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk Initialize the SDK and set up the back button to navigate the browser history. Ensure the SDK is initialized before using its components. The onClick handler returns a function to unbind the event listener. ```typescript import { init, backButton } from '@tma.js/sdk'; // Init the package and actualize all global dependencies. init(); // Mount the back button component and retrieve its actual // state. backButton.mount(); // When a user clicked the back button, go back in the // navigation history. const off = backButton.onClick(() => { off(); window.history.back(); }); ``` -------------------------------- ### useRawLaunchParams Hook Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-react Returns launch parameters in a raw format from any known source. ```APIDOC import { useRawLaunchParams } from '@tma.js/sdk-react'; function Component() { console.log(useRawLaunchParams()); // Example output: // tgWebAppBotInline=0&tgWebAppData=%7B%22user%22%3A%7B%7D... } ``` -------------------------------- ### Start Parameter Validation Regex Source: https://docs.telegram-mini-apps.com/platform/start-parameter Use this regular expression to validate the characters and length of the start parameter. It allows alphanumeric characters, underscores, and hyphens, up to 512 characters. ```regex /^[\w-]{0,512}$/ ``` -------------------------------- ### web_app_setup_main_button Source: https://docs.telegram-mini-apps.com/platform/methods Updates the Main Button settings. This method provides extensive control over the main button's appearance and behavior, including text, color, and visibility. ```APIDOC ## web_app_setup_main_button ### Description Updates the Main Button settings. ### Parameters #### Request Body - **is_visible** (boolean) - Optional - Should the button be displayed. - **is_active** (boolean) - Optional - Should the button be enabled. - **is_progress_visible** (boolean) - Optional - Should loader inside the button be displayed. Use this property in case, some operation takes time. This loader will make user notified about it. - **text** (string) - Optional - Text inside the button. - **color** (string) - Optional - The button background color in `#RRGGBB` format. - **text_color** (string) - Optional - The button text color in `#RRGGBB` format. - **has_shine_effect** (boolean) - Optional - Should the button have a shining effect. Available since v7.8. ``` -------------------------------- ### Receive Event Example for Native Platforms Source: https://docs.telegram-mini-apps.com/platform/events Demonstrates how Telegram native applications emit events by calling globally defined JavaScript functions. This example shows calling `receiveEvent` for a 'popup_closed' event. ```typescript window.Telegram.WebView.receiveEvent('popup_closed', { button_id: 'cancel' }); ``` -------------------------------- ### Get Hash Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the initialization data signature. Returns a string or `undefined`. ```typescript initData.hash(); // 'group' ``` -------------------------------- ### Initialize SDK and Mount Back Button Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-react Initialize the SDK and mount the Back Button component for integration into your React application. ```tsx import ReactDOM from 'react-dom/client'; import { init, backButton } from '@tma.js/sdk-react'; import { BackButton } from './BackButton.js'; // Initialize the package. init(); // Mount the Back Button, so we will work with // the actual component properties. backButton.mount(); ReactDOM .createRoot(document.getElementById('root')!) .render(); ``` -------------------------------- ### Get signal value Source: https://docs.telegram-mini-apps.com/packages/tma-js-signals Retrieve the current value of a signal by calling the signal function. ```typescript console.log('The element is', isVisible() ? 'visible' : 'invisible'); ``` -------------------------------- ### Mounting and Unmounting Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/mini-app Demonstrates how to mount and unmount the miniApp component. It's crucial to mount themeParams before miniApp for proper property initialization. The `isMounted` signal indicates the component's mounted state. ```APIDOC ## Mounting To mount the component, use the `mount` method, it will update the `isMounted` signal. But to have proper properties' values, before mounting the `miniApp`, it is required to mount `themeParams`. ```ts import { miniApp, themeParams } from '@tma.js/sdk'; themeParams.mount(); miniApp.mount(); miniApp.isMounted(); // true ``` To unmount the component, use the `unmount` method: ```ts miniApp.unmount(); miniApp.isMounted(); // false ``` ``` -------------------------------- ### Create Mini App with npx Source: https://docs.telegram-mini-apps.com/packages/tma-js-create-mini-app Use this command to scaffold a new Telegram Mini App project using npx. ```bash npx @tma.js/create-mini-app@latest ``` -------------------------------- ### Signal Mini App Ready Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/mini-app Call the ready method to signal that the Mini App is ready to be displayed. This hides the loading placeholder and shows the app. Call this early for a better user experience. ```typescript miniApp.ready(); ``` -------------------------------- ### Get User Data Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve an object containing information about the current user. Returns the `User` object or `undefined`. ```typescript initData.user(); // { // added_to_attachment_menu: false, // allows_write_to_pm: true, // is_premium: true, // first_name: 'Pavel', // id: 78262681, // is_bot: false, // last_name: 'Durov', // language_code: 'ru', // photo_url: 'https://example.com/image.png', // username: 'durove', // } ``` -------------------------------- ### Get Init Data State Object Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the initialization data as an object. Returns the `InitData` object or `undefined`. ```typescript initData.state(); ``` -------------------------------- ### Get Raw Init Data Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the raw string representation of the initialization data. Returns a string or `undefined`. ```typescript initData.raw(); // 'user=...&chat=...&...' ``` -------------------------------- ### Get All Keys from Cloud Storage Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/cloud-storage Retrieve a list of all keys currently stored in the cloud storage. This is an asynchronous operation. ```typescript const keys = await cloudStorage.getKeys(); // ['a', 'b', 'c'] ``` -------------------------------- ### Mounting and Unmounting Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/main-button Learn how to mount and unmount the Main Button component to enable or disable its functionality. Ensure Theme Params are mounted first. ```APIDOC ## Mounting Before using this component, it is necessary to mount it to work with properly configured properties. To do so, use the `mount` method. It will update the `isMounted` signal. ```ts import { mainButton } from '@tma.js/sdk'; mainButton.mount(); mainButton.isMounted(); // true ``` To unmount, use the `unmount` method: ```ts mainButton.unmount(); mainButton.isMounted(); // false ``` WARNING This component's properties depend on values from the Theme Params component. Make sure to mount Theme Params before using the Main Button. ``` -------------------------------- ### Get Current Time Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/uncategorized Retrieves the current Telegram server time. Returns a JavaScript Date object. This function is asynchronous. ```typescript import { getCurrentTime } from '@tma.js/sdk'; const time = await getCurrentTime(); // Date ``` -------------------------------- ### Mounting and Unmounting Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/theme-params Demonstrates how to mount and unmount the theme parameters component. Mounting makes the component active and updates its `isMounted` status. ```APIDOC ## Mounting Before using the component, it must be mounted. To mount the component, use the `mount` method. It will update the `isMounted` signal. ```ts import { themeParams } from '@tma.js/sdk'; themeParams.mount(); themeParams.isMounted(); // true ``` To unmount, use the `unmount` method: ```ts themeParams.unmount(); themeParams.isMounted(); // false ``` ``` -------------------------------- ### Get Chat Type Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the type of chat from which the Mini App was opened. This is only returned for applications opened by direct link. ```typescript initData.chatType(); // 'group' ``` -------------------------------- ### Get Can Send After Date Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the time after which a message can be sent, formatted as a `Date` object. Returns a `Date` object or `undefined`. ```typescript initData.canSendAfterDate(); // Date(1727368897600) ``` -------------------------------- ### Event: `accelerometer_failed` Source: https://docs.telegram-mini-apps.com/platform/events This event indicates that there was a failure in starting the accelerometer data tracking. It includes an error message detailing the issue. ```APIDOC ## `accelerometer_failed` Event ### Description Fired when the system fails to start tracking accelerometer data. Available since version 8.0. ### Parameters * **error** (`string`) - A message describing the occurred error. ``` -------------------------------- ### Mount Mini App and Theme Parameters Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/mini-app Mount the Mini App component and its dependencies. Ensure themeParams are mounted before the miniApp for correct property values. The isMounted signal indicates the component's status. ```typescript import { miniApp, themeParams } from '@tma.js/sdk'; themeParams.mount(); miniApp.mount(); miniApp.isMounted(); // true ``` -------------------------------- ### Get Raw Init Data with useRawInitData Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk-react Retrieve init data in its raw JSON string format using the `useRawInitData` hook. ```ts import { useRawInitData } from '@tma.js/sdk-react'; function Component() { console.log(useRawInitData()); // '{"user":...,"auth_date":...,"query_id":...,...}' } ``` -------------------------------- ### Prompt to Add Mini App to Home Screen Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/home-screen Use this function to prompt the user to add the Mini App to their device's home screen. Ensure the SDK is initialized before calling. ```typescript import { addToHomeScreen } from '@tma.js/sdk'; addToHomeScreen(); ``` -------------------------------- ### hash() Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieves the initialization data signature. ```APIDOC ## hash() ### Description Returns an initialization data signature. ### Return type `string | undefined` ### Example ```ts initData.hash(); // 'group' ``` ``` -------------------------------- ### Get All Theme Parameters Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/theme-params Returns an object containing all current theme parameters, where keys are parameter names and values are their RGB representations. ```typescript themeParams.state(); // Record; ``` -------------------------------- ### Get Chat Instance Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve a global identifier for the chat from which the Mini App was opened. This is only returned for applications opened by direct link. ```typescript initData.chatInstance(); // 'group' ``` -------------------------------- ### web_app_setup_secondary_button Source: https://docs.telegram-mini-apps.com/platform/methods Updates the Secondary Button settings. Available since v7.10. ```APIDOC ## web_app_setup_secondary_button ### Description The method that updates the Secondary Button settings. ### Parameters #### Query Parameters - **is_visible** (boolean) - Optional - Should the button be displayed. - **is_active** (boolean) - Optional - Should the button be enabled. - **is_progress_visible** (boolean) - Optional - Should loader inside the button be displayed. Use this property in case, some operation takes time. This loader will make user notified about it. - **color** (string) - Optional - The button background color in `#RRGGBB` format. - **text_color** (string) - Optional - The button text color in `#RRGGBB` format. - **has_shine_effect** (boolean) - Optional - Should the button have a shining effect. - **position** (string) - Optional - Position of the secondary button. It applies only if both the main and secondary buttons are visible. Supported values: `left`, `right`, `top`, `bottom`. ``` -------------------------------- ### Get Query ID Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the unique session ID of the Mini App, used for methods like `answerWebAppQuery`. Returns a string or `undefined`. ```typescript initData.queryId(); // 'hSvhacj28716' ``` -------------------------------- ### Get Auth Date Source: https://docs.telegram-mini-apps.com/packages/tma-js-sdk/features/init-data Retrieve the initialization data creation date using the `authDate` signal. Returns a `Date` object or `undefined` if not available. ```typescript initData.authDate(); // Date(1727368894000) ``` -------------------------------- ### web_app_setup_closing_behavior Source: https://docs.telegram-mini-apps.com/platform/methods Updates the current closing behavior of the Mini App. This allows you to control whether the user is prompted before closing the application. ```APIDOC ## web_app_setup_closing_behavior ### Description Updates current closing behavior. ### Parameters #### Request Body - **need_confirmation** (boolean) - Required - Will user be prompted in case, an application is going to be closed. ```