A secure authentication system that leverages Telegram Bot API for OTP verification in Next.js applications.
Check out our demo video to see Next.js Telegram Authentication in action:
- 🔐 Secure authentication using Telegram bots and OTP verification
- 🌐 Next.js API routes for webhook handling
- 📱 Mobile-friendly contact sharing
- 🔄 OTP regeneration with expiration control
- 🗄️ MongoDB integration for user and OTP storage
- 🌍 Multilingual support (English/Uzbek/Korean)
- 🔒 JWT token generation for authenticated sessions
- 🧹 Automatic keyboard removal after contact sharing
- 📨 Welcome messages personalized with user's name
- 🔔 Comprehensive message handling and error responses
- ⏱️ Time-limited OTP codes (1-minute expiration)
- 🛑 Prevention of duplicate OTP generation
- User Interaction: Users interact with your Telegram bot using
/start
or/login
commands - Contact Sharing: Bot requests user's contact information via Telegram's native contact sharing
- OTP Generation: A 6-digit OTP is generated and sent to the user via Telegram
- Verification: User verifies their identity by submitting the OTP through your web application
- Authentication: Upon successful verification, a JWT token is issued for secure sessions
- Node.js 16.x or later
- MongoDB database
- Telegram Bot (created via @BotFather)
- Next.js 14.x or later
- ngrok (for local development)
Create a .env.local
file in the root directory with the following variables:
# Telegram Bot
BOT_TOKEN=your_telegram_bot_token
WEBHOOK_URL=https://your-domain.com/api/telegram/webhook
# MongoDB
MONGODB_URI=mongodb+srv://your-connection-string
# JWT
JWT_SECRET=your_jwt_secret_key
-
Clone the repository:
git clone https://github.com/yourusername/next-telegram-auth.git cd next-telegram-auth
-
Install dependencies:
npm install
-
Set up your environment variables as described above
-
Run the development server:
npm run dev
For local development, you'll need to expose your local server to the internet so Telegram can send webhook updates. ngrok is the perfect tool for this:
-
Install ngrok:
# macOS with Homebrew brew install ngrok # Windows choco install ngrok # Or download from https://ngrok.com/download
-
Start your Next.js development server:
npm run dev
-
Start ngrok to create a secure tunnel to your local server:
ngrok http 3000
-
Update your Telegram bot webhook using the ngrok URL:
curl -F "url=https://YOUR-NGROK-URL/api/telegram/webhook" https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook
-
Update your
.env.local
file with the ngrok URL:WEBHOOK_URL=https://YOUR-NGROK-URL/api/telegram/webhook
-
You can now test your bot with Telegram while developing locally!
Note: Each time you restart ngrok, you'll get a new URL and will need to update your webhook.
Vercel is the ideal platform for Next.js applications and makes deployment straightforward:
-
Push your code to a Git repository (GitHub, GitLab, or Bitbucket)
-
Import your project in Vercel:
- Go to Vercel Dashboard
- Click "New Project"
- Select your repository
- Click "Import"
-
Configure environment variables:
- Add all required environment variables in the Vercel project settings:
BOT_TOKEN
MONGODB_URI
JWT_SECRET
- Add all required environment variables in the Vercel project settings:
-
Deploy:
- Click "Deploy"
- Wait for the deployment to complete
-
Update your Telegram webhook:
- After deployment, update your bot's webhook URL with your Vercel domain:
curl -F "url=https://your-project.vercel.app/api/telegram/webhook" https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook
-
Verify webhook setup:
curl https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo
Note: Unlike local development with ngrok, once deployed to Vercel, your bot will automatically work with the persistent public URL without requiring any tunneling.
- Create a new project in Railway
- Connect your GitHub repository
- Add environment variables
- Deploy and update webhook URL
- Import your repository to Netlify
- Configure build settings (
next build
as build command) - Add environment variables
- Deploy and update webhook URL
Important: For any deployment platform, ensure that serverless function timeout limits are sufficient for your webhook processing. Vercel's limit is 10 seconds on hobby plans.
/
├── app/ # Next.js 14 app directory
├── api/ # API Routes
│ ├── telegram/
│ │ ├── webhook.ts # Telegram webhook handler
│ │ └── verify.ts # OTP verification endpoint
├── lib/
│ └── mongoose.ts # Database connection utility
├── models/
│ ├── otp.ts # OTP model schema
│ └── user.ts # User model schema
└── components/ # React components
Handles incoming Telegram updates through webhooks.
Verifies OTPs and issues JWT tokens.
Request Body:
{
"otp": "123456"
}
Success Response:
{
"success": true,
"phoneNumber": "+1234567890",
"telegramData": {
"id": 123456789,
"first_name": "John",
"last_name": "Doe",
"username": "johndoe"
},
"token": "your.jwt.token"
}
/start
- Initiates the authentication process/login
- Generates a new OTP for authentication/test
- Test command to verify bot functionality
- User receives a personalized welcome message in their preferred language (English, Uzbek, or Korean)
- A single-tap contact sharing button appears
- After sharing contact, the keyboard is automatically removed for a cleaner interface
- OTP is delivered with clear instructions in multiple languages
- Users can generate new codes with a single tap if needed
- Informative error messages guide users when something goes wrong
The bot supports three languages:
- 🇺🇿 Uzbek
- 🇺🇸 English
- 🇰🇷 Korean
All user-facing messages are presented in these languages for maximum accessibility.
Stores user information linked to their Telegram account:
phoneNumber
: User's phone number (unique)telegramId
: Telegram user IDfirstName
: User's first name from TelegramlastName
: User's last name from Telegramusername
: Telegram usernamephotoUrl
: Profile photo URL (optional)createdAt
: Account creation timestamplastLogin
: Last login timestamp
Manages OTP codes with auto-expiration:
otp
: 6-digit verification codephoneNumber
: Associated phone numbertelegramData
: Telegram user informationexpiresAt
: Expiration timestamp (with TTL index)
- Automatic OTP expiration after 1-2 minutes
- MongoDB TTL index for automatic cleanup of expired OTPs
- Secure JWT token generation for authenticated sessions
- One-time use OTPs (deleted after verification)
- Prevention of duplicate OTP generation
- Clean keyboard removal after authentication
- Error handling for invalid messages or commands
- Personalized Greetings: Bot welcomes users by name
- Smart OTP Management: Prevents unnecessary OTP regeneration if existing code is valid
- Fallback Error Handling: Graceful error management for unhandled message types
- Intelligent Message Processing: Contextual responses based on user interaction stage
- Keyboard Management: Automatic cleanup of UI elements after use
-
Webhook not receiving updates
- Verify your webhook URL is correctly set in Telegram
- Check for any error responses in server logs
- For local development: ensure ngrok tunnel is running
-
OTP not being generated
- Verify MongoDB connection is working
- Check server logs for any database errors
- Ensure the Telegram user ID is being correctly extracted
-
JWT token issues
- Verify your JWT_SECRET is properly set
- Check that the token generation code has correct payload structure
-
Deployment issues
- Check if all environment variables are correctly set
- Verify the webhook URL has been updated after deployment
- Review logs in your deployment platform
The webhook handler includes detailed logging:
- Raw request body logging
- Parsed update logging
- Error capture and reporting
You can monitor these logs in your terminal while developing locally or in your deployment platform's logging interface.
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.