How to Make a Telegram Mini App: Step-by-Step Tutorial
DEV Community

How to Make a Telegram Mini App: Step-by-Step Tutorial

To make a Telegram Mini App, create a bot with @botfather, build a web page that loads Telegram's telegram-web-app.js script, host it on an HTTPS URL, and set that URL as the bot's menu button or Main Mini App.

The page reads the user's theme and launch data from window.Telegram.WebApp, and your server checks that launch data (initData) with an HMAC-SHA256 signature derived from your bot token before it trusts who the user is. Everything else is ordinary web development.

This tutorial builds a working daily check-in app in plain HTML, JavaScript, and Node.js: the user opens it from the bot, sees their name and points, and taps the bottom button once a day for 10 points. It is small, but it has every part a real Mini App needs: theming, the main button, haptics, server-side validation, and server-side state.

Every Telegram API name comes from Telegram's own docs, mainly the Mini Apps documentation, checked on October 22, 2026 (the newest change listed there is Bot API 10.1 from June 11, 2026).

How a Mini App works: who does what

A Mini App is your own website that Telegram opens in a web view connected to your bot. Telegram adds two things: a JavaScript bridge to the Telegram app, and signed launch data about the user.

  • Bot - Where it runs: Telegram. Its job: Owns the token, the menu button, and the Mini App settings you make in @botfather
  • Front end - Where it runs: Telegram's web view on the user's device. Its job: Your HTML, CSS, and JavaScript, in plain code or any framework
  • telegram-web-app.js - Where it runs: Inside your page. Its job: Exposes window.Telegram.WebApp: initData, themeParams, MainButton, HapticFeedback, openLink, openInvoice, and more
  • Your server - Where it runs: Your HTTPS host. Its job: Validates initData, stores users and balances, creates invoices
  • Bot token - Where it runs: Your server only. Its job: Talks to the Bot API and is the base of the validation key

One rule shapes everything else. Telegram's docs warn that initDataUnsafe should not be trusted, and that you should use initData on your server only after validating it. Anyone can fake the browser object, so it is for showing a name, never for deciding who gets points.

Step 1: create the bot with BotFather

Open @BotFather in Telegram and send /newbot. BotFather also has its own Mini App with the same functions, if you prefer buttons to commands.

Choose a display name, then a username. Telegram's bot features page says usernames are 5 to 32 characters, may only use Latin letters, numbers, and underscores, must end in "bot", and cannot be changed later.

Copy the token BotFather sends, in the form 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw (Telegram's sample). Anyone with it can control your bot, and section 4.5 of Telegram's Bot Platform Developer Terms prohibits making such credentials public. If it leaks, /token generates a new one.

Keep the token in an environment variable on your server, such as BOT_TOKEN, never in your HTML, JavaScript bundle, or Git repository. Make a second bot for testing, too, as Telegram suggests, so you never test on real users.

Step 2: build the front end with telegram-web-app.js

Create public/index.html. Telegram's docs say to place telegram-web-app.js in the <head> before any other scripts; the ?64 suffix is the version shown in the docs on the day we checked.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://telegram.org/js/telegram-web-app.js?64"></script>
<style>
body { margin: 0; padding: 24px 16px; font-family: system-ui, sans-serif; background: var(--tg-theme-bg-color, #ffffff); color: var(--tg-theme-text-color, #000000); }
.hint { color: var(--tg-theme-hint-color, #707579); }
.points { font-size: 48px; font-weight: 700; color: var(--tg-theme-accent-text-color, #2481cc); }
</style>
</head>
<body>
<h1 id="hello">Loading...</h1>
<p class="points" id="points">0</p>
<p class="hint" id="status">Claim 10 points once a day.</p>
<script>
const tg = window.Telegram.WebApp;
tg.ready();
tg.expand();
async function api(path) {
const res = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ initData: tg.initData }), });
return { ok: res.ok, status: res.status, data: await res.json() };
}
function show(data) {
document.getElementById('points').textContent = data.points;
}
api('/api/session').then(({ ok, data }) => {
if (!ok) {
document.getElementById('hello').textContent = 'Open this app from Telegram';
return;
}
document.getElementById('hello').textContent = 'Hi, ' + data.name;
show(data);
tg.MainButton.setText('Claim daily points').show();
});
tg.MainButton.onClick(async () => {
tg.MainButton.showProgress();
const { ok, status, data } = await api('/api/claim');
tg.MainButton.hideProgress();
if (ok) {
show(data);
tg.HapticFeedback.notificationOccurred('success');
document.getElementById('status').textContent = 'Claimed. Come back tomorrow.';
} else if (status === 409) {
tg.HapticFeedback.notificationOccurred('warning');
tg.showAlert('You already claimed today.');
} else {
tg.HapticFeedback.notificationOccurred('error');
}
});
</script>
</body>
</html>

What each part does:

  • tg.ready() tells Telegram the app can be shown and hides the loading placeholder. Telegram recommends calling it as early as possible, once the essential interface is loaded.
  • tg.expand() asks for the full available height when Telegram opens the app at part height. A Main Mini App and a direct link already open at full height by default.
  • Theme colors. Each themeParams color is also a CSS variable, such as --tg-theme-bg-color, so the page matches the user's day or night theme; the value after the comma is the fallback in a normal browser. If you draw with JavaScript, read tg.themeParams and listen for themeChanged.
  • tg.MainButton is the native button at the bottom of the Telegram interface. Its methods return the button, so they chain, and Telegram recommends showProgress() when the action may take a while.
  • tg.HapticFeedback.notificationOccurred() takes success, warning, or error. For taps in games, use impactOccurred() with a style such as light or heavy.
  • tg.initData, the raw signed string, goes to the server on every call. The page never sends a user ID of its own.

Step 3: validate initData on the server in Node.js

Telegram documents the check in Validating data received via the Mini App. In short:

  1. Parse initData as a query string and take out hash.
  2. Sort the remaining fields alphabetically and join them as key=value lines separated by a line feed. This is the data-check-string.
  3. Compute the secret key: HMAC-SHA256 of the bot token, with the constant string WebAppData as the key.
  4. Compute HMAC-SHA256 of the data-check-string with that secret key, in hex, and compare it with hash.
  5. Check auth_date to reject old data.

In Node.js, with only the built-in crypto module, save this as validate-init-data.js:

const crypto = require('node:crypto');
function validateInitData(initData, botToken, maxAgeSeconds = 3600) {
if (typeof initData !== 'string' || initData === '') return null;
const params = new URLSearchParams(initData);
const hash = params.get('hash');
if (!hash || !/^[0-9a-f]{64}$/.test(hash)) return null;
params.delete('hash');
const dataCheckString = [...params.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([key, value]) => `${key}=${value}`).join('\n');
const secretKey = crypto.createHmac('sha256', 'WebAppData').update(botToken).digest();
const expected = crypto.createHmac('sha256', secretKey).update(dataCheckString).digest();
if (!crypto.timingSafeEqual(expected, Buffer.from(hash, 'hex'))) return null;
const authDate = Number(params.get('auth_date'));
const age = Math.floor(Date.now() / 1000) - authDate;
if (!Number.isInteger(authDate) || age > maxAgeSeconds) return null;
let user = null;
try { user = JSON.parse(params.get('user')); } catch { return null; }
if (!user || typeof user.id !== 'number') return null;
return { user, authDate, startParam: params.get('start_param') };
}
module.exports = { validateInitData };

The details that trip people up:

  • Key order in the first HMAC. WebAppData is the key and the bot token is the message; swapping them is the most common bug. Use the result as raw bytes, not hex.
  • Only hash comes out. Every other field stays in the data-check-string, including signature. Telegram added that field with Bot API 8.0 so third parties can check the data with Telegram's Ed25519 public key without knowing your token; your own HMAC check treats it like any other field.
  • Constant-time comparison. crypto.timingSafeEqual does not leak timing, and Node's docs say it throws when the two inputs have different byte lengths. The regular expression makes sure hash is exactly 64 hex characters first. What is HMAC? explains why a plain === is not enough.
  • auth_date is the time the app was opened. One hour is the default above. If users keep your app open longer, validate once at launch and issue your own short-lived session token, rather than accepting days-old launch data.
  • Telegram user IDs are big. Telegram says user.id can have more than 32 significant bits (at most 52), so store it as a 64-bit integer, such as BIGINT, never a 32-bit INT.

Now the server. Install Express with npm install express and save this as server.js:

const express = require('express');
const { validateInitData } = require('./validate-init-data');
const BOT_TOKEN = process.env.BOT_TOKEN;
if (!BOT_TOKEN) throw new Error('Set BOT_TOKEN');
const app = express();
app.use(express.json({ limit: '10kb' }));
app.use(express.static('public'));
const points = new Map();
const lastClaim = new Map();
function telegramUser(req, res, next) {
const result = validateInitData(req.body?.initData, BOT_TOKEN);
if (!result) return res.status(401).json({ error: 'invalid init data' });
req.tgUser = result.user;
next();
}
app.post('/api/session', telegramUser, (req, res) => {
const id = req.tgUser.id;
res.json({ name: req.tgUser.first_name, points: points.get(id) ?? 0 });
});
app.post('/api/claim', telegramUser, (req, res) => {
const id = req.tgUser.id;
const today = new Date().toISOString().slice(0, 10);
if (lastClaim.get(id) === today) {
return res.status(409).json({ error: 'already claimed today', points: points.get(id) ?? 0 });
}
lastClaim.set(id, today);
points.set(id, (points.get(id) ?? 0) + 10);
res.json({ points: points.get(id) });
});
app.listen(process.env.PORT ?? 3000);

Every API route runs telegramUser first, so handlers only see validated users. The Map objects keep the example short; use a database in production. Start it with BOT_TOKEN=your-token node server.js.

Test the validation locally with a generated test vector

You do not need Telegram to test the check. This helper signs a launch string the way Telegram does, using a fake token. Save it as make-test-init-data.js:

const crypto = require('node:crypto');
function makeTestInitData(botToken, fields) {
const params = new URLSearchParams(fields);
const dataCheckString = [...params.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([key, value]) => `${key}=${value}`).join('\n');
const secretKey = crypto.createHmac('sha256', 'WebAppData').update(botToken).digest();
params.set('hash', crypto.createHmac('sha256', secretKey).update(dataCheckString).digest('hex'));
return params.toString();
}
module.exports = { makeTestInitData };

Then a short test, check-init-data.js: a valid string must pass, and a changed user ID or a different token must fail.

const assert = require('node:assert');
const { validateInitData } = require('./validate-init-data');
const { makeTestInitData } = require('./make-test-init-data');
const token = '123456789:TEST-token-for-local-checks-only';
const initData = makeTestInitData(token, { query_id: 'AAHtest', user: JSON.stringify({ id: 42, first_name: 'Ana' }), auth_date: String(Math.floor(Date.now() / 1000)), });
assert.strictEqual(validateInitData(initData, token).user.id, 42);
assert.strictEqual(validateInitData(initData.replace('%22id%22%3A42', '%22id%22%3A43'), token), null);
assert.strictEqual(validateInitData(initData, '123456789:another-token'), null);
console.log('initData checks passed');

node check-init-data.js prints initData checks passed.

Why we also checked against an outside example: A helper that signs the same way as your validator can share its bugs, so we also ran the validator against the worked example in the community Telegram Mini Apps init data docs (age limit raised, since that sample is from 2022), and it passed.

All code on this page ran on Node.js 22 with Express 5.3; tampered, expired, and missing launch data got a 401.

Step 4: host it on HTTPS and connect it to the bot

Telegram's Bot API describes a Mini App URL as "an HTTPS URL", so production needs a real certificate. You have three practical options:

  • Your own host. Any server that runs Node.js behind HTTPS works. Serve the page and the API from the same origin, as server.js does, and you avoid CORS.
  • A tunnel while you develop. Cloudflare's Quick Tunnels give a local server a temporary trycloudflare.com URL with no account: run `cloudflared tunnel --url http://loc
Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.