Menu

Validating Telegram Mini App initData in Node.js without a library
📰

Validating Telegram Mini App initData in Node.js without a library

DEV Community: javascript·Kirill Vetrov·about 2 hours ago
#RI0jJdso
#devtojavascript#devto#dev#hash#const
Long article (922 words) — no AI summary yet.
Reading 0:00
15s threshold

A Telegram Mini App receives the user's identity in Telegram.WebApp.initData : a query string with user , auth_date , query_id and a hash . The client can send anything it likes, so the server has to check that hash before it trusts a single field. Node's crypto module is all it takes.

How Telegram signs the data

The algorithm is in the Telegram Mini Apps documentation:

Take every field except hash , sort them by key and join them as key=value lines with \n . That is the data-check-string.

The secret key is HMAC-SHA256 of the bot token, with the string WebAppData as the key.

The expected hash is HMAC-SHA256 of the data-check-string with that secret key, in hex.

The order in step 2 trips people up. WebAppData is the HMAC key and the bot token is the message, not the other way round.

The check

import { createHmac , timingSafeEqual } from "node:crypto" ;

export function checkInitData ( initData , botToken , maxAgeSeconds = 3600 ) { const params = new URLSearchParams ( initData ) ; const hash = params .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.