Skip to content

Verify Telegram webhooks

Verify that a webhook really came from Telegram before acting on it.

Identifier 'telegram'
Import import { verifyTelegram } from 'verihook/telegram'
Headers x-telegram-bot-api-secret-token
Signature No signature. Telegram sends the secret_token you passed to setWebhook.
Replay window None (the provider sends no timestamp)
result.eventType the update kind, e.g. message or callback_query

The secret_token you chose when calling setWebhook (1–256 characters: letters, digits, _ and -). It is not the bot token.

Store it in an environment variable (TELEGRAM_WEBHOOK_SECRET_TOKEN below) and never commit it.

import { verifyTelegram } from 'verihook/telegram';
export async function POST(request: Request) {
const result = await verifyTelegram(request, process.env.TELEGRAM_WEBHOOK_SECRET_TOKEN!);
if (!result.valid) {
console.warn(result.code, result.reason, result.hint);
return new Response('Invalid signature', { status: 401 });
}
console.log(result.eventType, result.event);
return Response.json({ received: true });
}

request can be a Fetch Request or { headers, body, url? } with the raw body. verifyWebhook('telegram', request, secret) from verihook does the same. Read why the raw body matters if verification fails behind a body parser.

app/api/webhooks/telegram/route.ts
import { createWebhookHandler } from 'verihook/next';
export const POST = createWebhookHandler('telegram', process.env.TELEGRAM_WEBHOOK_SECRET_TOKEN!, async (payload, result) => {
// Runs only for a valid signature
console.log(result.eventType, result.event);
});

Each adapter responds 401 to an invalid signature, 413 to a body over maxBodySize (2 MB by default) and 200 to a duplicate when you pass a dedupeStore.

  • If you called setWebhook without secret_token, Telegram sends no header and the request can’t be verified. Call it again with one.

signWebhook from verihook/testing builds a correctly signed Telegram request for your tests:

import { signWebhook } from 'verihook/testing';
import { verifyTelegram } from 'verihook/telegram';
const hook = await signWebhook('telegram', {
secret: 'telegram_secret_token',
payload: { id: 'evt_test' },
});
const result = await verifyTelegram(
{ headers: hook.headers, body: hook.body, url: hook.url },
hook.secret,
);
// result.valid === true

From the command line, npx verihook simulate telegram --url http://localhost:3000/webhooks/telegram sends one to your local server.

See Testing your handlers for supertest and Fetch Request examples.

Failed results carry a code and often a hint with the likely cause. See Troubleshooting for each error code.

Telegram’s webhook documentation