Fastify plugin for Telegram Mini Apps integration. Provides secure auth validation, type-safe decorators, and utilities for building Telegram Mini Apps backend with Fastify.
# npm
npm install fastify-tma
# pnpm
pnpm install fastify-tma
Import fastify-tma
and register.
import Fastify from 'fastify'
import { fastifyTMA } from 'fastify-tma'
const fastify = Fastify()
fastify.register(fastifyTMA, {
botToken: 'your-tg-bot-token'
})
fastify.addHook('onRequest', req => req.tmaValidate())
fastify.listen({ port: 3000 })
Afterwards, just use request.tmaInitData
in order to retrieve telegram user information:
fastify.get('/', async (request, reply) => {
return request.tmaInitData
})
However, in most cases we only want to check some routes in our application. To achieve this goal, you can transfer the verification logic to such a plugin, for example:
import fp from 'fastify-plugin'
import { fastifyTMA } from 'fastify-tma'
export default fp(async (fastify, opts) => {
await fastify.register(fastifyTMA, {
botToken: 'your-tg-bot-token'
})
fastify.decorate('tgValidate', async (req, reply) => {
try {
await req.tmaValidate()
}
catch (err) {
reply.send(err)
}
})
})
Then use the onRequest
of a route to protect it and access the telegram user information inside:
export default async function (fastify, opts) {
fastify.get(
'/',
{
onRequest: [fastify.tgValidate]
},
async (req, reply) => {
return req.tmaInitData
}
)
}
Make sure that you also check @fastify/auth plugin for composing more complex strategies.