Build Telegram Bot and Mini App in One Next.js Project
When developing within the Telegram ecosystem, many developers face a common pain point: how to manage both Bot and Mini App code simultaneously? The traditional approach involves deploying two separate projects, which not only increases maintenance costs but also easily leads to issues in data synchronization and payment processes.
On this page
On this page
Anti-detect browser for multi-account operations
- Independent browser profiles
- RPA automation
- Team collaboration
This article will showcase a brand-new development paradigm: using a single Next.js project to implement both a Telegram Bot and a Mini App, truly achieving one codebase, one deployment, seamless integration. You'll learn how to build a complete points-based game system, including daily check-in rewards, real Telegram Stars payments, and real-time notification features.
Why Choose Next.js for Unified Bot and Mini App Development?
In the traditional model, developers need to:
- Deploy the Bot backend service separately.
- Deploy the Mini App frontend application separately.
- Integrate data between the two projects.
- Maintain two sets of environment variables and configurations.
By using the Next.js all-in-one solution, you can:
- Manage all functionalities within a single codebase.
- Share API routes to handle Bot commands, Mini App requests, and payment logic.
- Deploy uniformly to platforms like Vercel, reducing operational costs.
- Achieve inherent data consistency, eliminating the need for extra synchronization mechanisms.
This approach is particularly suitable for rapidly validating ideas, developing MVP products, or for independent developers looking to launch projects quickly.
Core Feature Demonstration: What Can This Project Do?
We will build a points-based game system with the following features:
- Daily Check-in Rewards: Users can claim 100 points every 24 hours, with a real-time countdown display.
- Telegram Stars Payment: Users purchase points with real currency, supporting instant refund testing.
- Bot Command Handling: Supports common commands like
/startand/help, allowing users to launch the Mini App with a single click. - Real-time Notification Push: Operations like successful payments and refunds will be notified via Bot messages.
The entire system runs within a single Next.js application, ensuring seamless interaction between the Bot and the Mini App.
Prerequisites
Before you begin the development, you'll need to prepare the following tools:
- Telegram Account: To create a Bot and test the Mini App.
- Node.js 18+: If not installed, download it from nodejs.org.
- Ngrok: To create an HTTPS tunnel for local development, as Telegram requires Webhooks and Mini Apps to use HTTPS.
How to Get Ngrok
- Visit ngrok.com to register for a free account.
- Download the version for your operating system.
- Unzip it into a dedicated folder.
- Run
ngrok config add-authtoken <your_token>to bind your account. - Once completed, you can run
ngrok http 3000from that folder at any time.
Quick Project Setup (5 Minutes to Get Started)
1. Get Project Code and Install Dependencies
You can obtain the complete source code and detailed documentation from the relevant Telegram channel (specific links can be found in the original video description).
git clone <project_repository_url>
cd <project_directory>
npm install
2. Configure Environment Variables
Create a .env.local file in the project's root directory to store sensitive information:
TELEGRAM_BOT_TOKEN=your_bot_token
NEXT_PUBLIC_APP_URL=your_ngrok_url
Important Note: Ensure .env.local is added to .gitignore to prevent Bot Token leakage.
3. Create a Telegram Bot
- Open Telegram and search for BotFather.
- Send
/newbotto create a new Bot. - Set the Bot's name and username (which must end with
bot). - Copy the generated Bot Token and save it to
.env.local.
4. Start Ngrok and the Development Server
# Terminal 1: Start Ngrok
ngrok http 3000
# Terminal 2: Start Next.js development server
npm run dev
# Terminal 3: Set up Webhook
npm run webhook:setup
If everything goes smoothly, you will see the "Webhook set successfully" message.
5. Configure the Mini App Menu Button
- Return to BotFather, send
/mybots, and select your Bot. - Click Bot Settings → Menu Button.
- Enter the URL (using the HTTPS address provided by Ngrok) and the button text (e.g., "Play Game").
Now, when users open your Bot, they will see a button to launch the game, which will open the Mini App interface upon clicking!
Core Code Analysis: How Do the Bot and Mini App Work Together?
Webhook Endpoint: The Bot's Message Hub
All updates sent by Telegram (user commands, payment callbacks, etc.) are passed through the Webhook to the /api/telegram/webhook route.
The main message types handled include:
- User Commands:
/start,/help, etc. - Pre-payment Confirmation: Pre-checks after the user clicks the payment button.
- Successful Payment Callback: Confirms transaction completion and issues points.
- Refund Requests: Allows quick testing of the refund process during development.
When a user first sends /start, the Bot will immediately push a "Start Game" button, requiring no further guidance.
Telegram Stars Payment Flow
The core of the payment functionality lies in the /api/buy-points route:
- The user clicks "Buy Points" in the Mini App.
- The Telegram Bot API is called to create an invoice (
createInvoiceLink). - The invoice is displayed in Telegram's native payment interface.
- After the user completes the payment, the Webhook receives a notification.
- The system updates the user's points and sends a receipt message.
Key Configuration:
- Leave
provider_tokenblank (Telegram Stars mode). - Set
currencytoXTR. pricesare in units of Stars (not cents).
Developer Benefit: After each purchase, a receipt ID is returned. You can immediately test refunds using /refund <receipt_id> without waiting for approval or manual intervention. This is extremely efficient for testing the real payment process.
Daily Check-in Reward System
In the /api/claim-daily route, we've implemented a time-based incentive mechanism:
- Record the last claim time for each user.
- Check if 24 hours have passed.
- If less than 24 hours have passed, return the remaining countdown time.
- Upon successful claiming, issue 100 points and send a Telegram notification.
The frontend uses a real-time countdown component that updates every second, clearly showing users when they can claim again. This model can be extended to any game mechanic requiring time limits (e.g., energy regeneration, lottery cooldowns, etc.).
Production Deployment Considerations
Although this article uses in-memory storage for demonstration, real projects must be modified before going live:
- Database: Replace in-memory storage with PostgreSQL or MongoDB.
- User Authentication: Verify Telegram Web App data signatures to prevent forged requests.
- Rate Limiting: Prevent malicious point farming or abuse of payment interfaces.
- Log Monitoring: Integrate error tracking services (like Sentry).
- Webhook Security: Verify that requests truly originate from Telegram servers.
Recommended deployment platforms:
- Vercel: Zero-configuration deployment, automatic HTTPS.
- Heroku / Railway: Suitable for scenarios requiring long connections.
- Cloudflare Workers: Edge computing solution for global acceleration.
Remember to update the Webhook URL and Mini App Menu Link to your production domain when deploying.
Frequently Asked Questions (FAQ)
Why do I need Ngrok? Can't I just use localhost?
Telegram's Webhooks and Mini Apps both require the HTTPS protocol, which localhost cannot satisfy. Ngrok creates a publicly accessible HTTPS tunnel that forwards requests to your local development server.
How can I test real payments without spending money?
During the development phase, you can purchase a small amount of Telegram Stars (as little as a few cents) and then use the /refund command to get an instant refund. This allows you to test the payment, webhook callbacks, and refund logic using the real process, without needing to repeatedly top up.
Can I continue using in-memory storage in production?
Absolutely not. In-memory storage loses all data upon server restart. You must use a persistent database (like PostgreSQL) and have backup and migration plans in place.
What are the main advantages of the Next.js unified solution?
The biggest advantages are reduced development efficiency and maintenance costs. You won't need to:
- Manage two separate code repositories.
- Worry about frontend-backend data inconsistencies.
- Configure complex cross-origin requests and API integrations.
- Deploy and monitor two services separately.
All logic resides within a single project, leading to higher code reusability and faster bug identification.
Is this architecture suitable for large-scale applications?
It's perfectly adequate for MVP products and small to medium-sized applications. If your daily active users reach millions, it's recommended to split the Bot backend and Mini App frontend, using a microservices architecture and dedicated message queues to handle high concurrency.
Conclusion
Through the practical demonstration in this article, you've mastered the core skills for building an integrated Telegram Bot + Mini App application using Next.js. This development approach can help you quickly validate ideas, reduce development costs, and lay a solid foundation for future expansion. Start experimenting today and build your own Telegram mini-game in the shortest amount of time!
Simplify multi-account operations with MasLogin
Bring independent browser profiles, browser identity controls, proxy management, automation and team workflows into one workspace.


