I want to create a TMA (Telegram Mini App) using @twa-dev/sdk
. I don't any auth in the app but I need to pass a something like Telegram ID, etc. to my API endpoint to save/retrieve user related data in/from database.
Is there any property in @twa-dev/sdk
to implement this?
using nextjs/typescript
Steps 1 update ur root layout.tsx
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import Script from "next/script"; // Import the Script component from next/script
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<head>
<Script
src="https://telegram.org/js/telegram-web-app.js"
strategy="beforeInteractive" // This ensures the script is loaded before interactivity
/>
</head>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}
steps 2 go to were you want to use the data eg page.tsx
"use client";
import WebApp from '@twa-dev/sdk'
interface UserData{
id:number;
firstName?:string;
lastName?:string;
username?:string;
photo_url?:string;
}
const Home=()=>{
const [usertData,setUserData]=useState<UserData | null>(null);
useEffect(() => {
// Check if WebApp SDK is available and only use it on the client side
if (typeof window !== "undefined" && WebApp.initDataUnsafe.user) {
setUserData(WebApp.initDataUnsafe.user as UserData);
}
}, []);
return(
<div>
<ul>
<img src={usertData?.photo_url || image_url}>
<li>{usertData?.id} </li>
<li>{usertData?.firstName} </li>
<li>{usertData?.username} </li>
</ul>
</div>
)
}
export default Home;