LaunchFast Logo LaunchFast

Create a Telegram Bot in Next.js App Router: A Step-by-Step Guide

Rishi Raj Jain
Create a Telegram Bot in Next.js

In this guide, you will learn how to use Grammy SDK to create a telegram bot in a Next.js application. You will go through the process of setting up a new Next.js project, configuring Grammy SDK with Next.js, and create an API route to respond to user messages.

Prerequisites

You’ll need the following:

Table Of Contents

Create a new Next.js application

Let’s get started by creating a new Next.js project. Open your terminal and run the following command:

npx create-next-app@latest my-app

When prompted, choose:

  • Yes when prompted to use TypeScript.
  • No when prompted to use ESLint.
  • Yes when prompted to use Tailwind CSS.
  • No when prompted to use src/ directory.
  • Yes when prompted to use App Router.
  • No when prompted to customize the default import alias (@/*).

Once that is done, move into the project directory and start the app in development mode by executing the following command:

cd my-app
npm run dev

The app should be running on localhost:3000. Now, let’s close the developement server to install Grammy SDK.

Integrate Grammy SDK in your Next.js project

First, run the following command to install the Grammy SDK:

  • grammy: A package that makes it easy to create Telegram bots.
npm install grammy

Further, perform the following code addition in next.config.mjs file to allow grammy to use Node.js specific features in Next.js App Router:

// File: next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: { // [!code ++]
    serverComponentsExternalPackages: ['grammy'], // [!code ++]
  }, // [!code ++]
}

export default nextConfig

Now, let’s move on to creating an API route to respond to user messages with the bot.

Create a Telegram Webhook API Route

To create an API route that responds to the POST request by Telegram to respond to user messages interacting with your bot, create a file named route.ts in the app/api/bot directory with the following code:

// File: app/api/bot/route.ts

export const dynamic = 'force-dynamic'

export const fetchCache = 'force-no-store'

import { Bot, webhookCallback } from 'grammy'

const token = process.env.TELEGRAM_BOT_TOKEN

if (!token) throw new Error('TELEGRAM_BOT_TOKEN environment variable not found.')

const bot = new Bot(token)
bot.on('message:text', async (ctx) => {
  await ctx.reply(ctx.message.text)
})

export const POST = webhookCallback(bot, 'std/http')

The code above does the following:

  • Makes sure that each request is processed dynamically and responses are not cached.
  • Imports the Bot and webhookCallback helpers from the Grammy SDK.
  • Initializes a Telegram Bot API compatible bot instance.
  • Exports the webhookCallback helper relying on standard HTTP Request and Response mechanism as the handler to incoming POST requests.

With that done, let’s move on to deploying the application.

Deploy to Vercel

The code is now ready to deploy to Vercel. Use the following steps to deploy:

  • Start by creating a GitHub repository containing your app’s code.
  • Then, navigate to the Vercel Dashboard and create a New Project.
  • Link the new project to the GitHub repository you have just created.
  • In Settings, update the Environment Variables to match those in your local .env file.
  • Deploy! 🚀

Set the API Route as Telegram Bot Webhook

To configure Telegram to invoke the /api/bot route to respond to user interactions with your bot, run the following command after updating it with your Telegram Bot Token and Vercel Deployment URL.

curl https://api.telegram.org/bot<telegram_bot_token>/setWebhook?url=https://<your-deployment.vercel>.app/api/bot

Conclusion

In this guide, you learned how to integrate Grammy SDK to create your own Telegram Bot in Next.js. Further, you learnt how to point Telegram Bot to your custom deployment URL to respond to user messages with the bot.

If you have any questions or comments, feel free to reach out to me on Twitter.

Learn More Injecting Environment Variables Dynamically in Cloudflare Pages → Using Unplugin Icons in Next.js: A Step-by-Step Guide → Using Unplugin Icons in SvelteKit: A Step-by-Step Guide →