How to get telegram user id using WebApp @twa-dev/sdk and typescript
- User
How to get telegram user id using WebApp @twa-dev/sdk and typescript
- Assistant
How to get telegram user id using WebApp @twa-dev/sdk and typescript
To get a Telegram user ID using the Telegram Web Apps SDK (@twa-dev/sdk) with TypeScript, you first need to set up your environment to use the SDK in a web context. Here's a step-by-step guide to help you achieve this:
Set up your Project:
mkdir telegram-webapp
cd telegram-webapp
npm init -y
Install Necessary Packages:
npm install typescript @twa-dev/sdk @types/node --save-dev
Initialize TypeScript in your Project:
tsconfig.json:
npx tsc --init
Set Up the HTML File:
index.html) within your project directory:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Telegram WebApp</title>
</head>
<body>
<div id="app"></div>
<script src="dist/index.js" type="module"></script>
</body>
</html>
Develop your Script using TypeScript:
index.ts) where you will use the SDK to get the user ID:
import { MainButton, initDataUnsafe } from '@twa-dev/sdk';
function startApp() {
// Initialize the Web App with the context
const telegram = window.Telegram.WebApp;
// Access the user property which contains the user ID
const userId = initDataUnsafe.user?.id;
// Display the user ID in the web page or log it
if (userId) {
document.getElementById('app')!.innerText = `User ID: ${userId}`;
} else {
document.getElementById('app')!.innerText = 'User ID not available';
}
}
// Execute the function to start the app
startApp();
Compile TypeScript to JavaScript:
npx tsc
dist directory with the compiled JavaScript files.Test your Web App:
http-server:
npx http-server .
http://127.0.0.1:8080).Deploy as a Telegram WebApp:
Remember to handle errors or cases where the user ID may not be available (e.g., null or undefined values). Testing directly over Telegram will give you the real user ID after setting up properly with BotFather and the Telegram context.
Not yet included in a published release.