Telegram Better Auth Plugin
The `telegram-better-auth` package provides a plugin to seamlessly integrate Telegram login functionality into applications built with the `better-auth` authentication framework. This library, currently at version `0.0.8`, offers a streamlined approach to allowing users to authenticate via their Telegram accounts, managing both the server-side logic for verifying authorization data and the client-side interaction with the Telegram Login Widget. While a formal release cadence is not explicitly stated, the frequent minor version bumps (0.0.x) suggest active development. A key differentiator is its tightly coupled design with `better-auth`, abstracting complex Telegram API interactions, such as the generation of temporary emails based on Telegram IDs. Proper functioning requires a valid Telegram bot token and ensuring the bot is linked to the application's domain via BotFather.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'telegram')
cause The `telegram` plugin was not correctly registered in the `betterAuth` instance, or the `signIn.telegram` method was called on an `authClient` instance without `telegramClient` plugin.fixEnsure `telegram` plugin is added to the `plugins` array of `betterAuth` on the server and `telegramClient` plugin is added to `createAuthClient` on the client. Verify correct import paths. -
Error: Telegram login data verification failed: Invalid hash
cause The `hash` provided by the Telegram Login Widget does not match the server-calculated hash, indicating tampered data or an incorrect bot token configuration.fixVerify that the `botToken` in your server-side `telegram` plugin configuration is correct and matches the token of the bot linked to your domain. Ensure no modifications occur to the data object received from Telegram before sending it to the server. -
Error: Telegram login data verification failed: Auth date out of range
cause The `auth_date` from the Telegram Login Widget is too old (typically more than 24 hours ago), meaning the authentication session has expired.fixEnsure the user re-authenticates via the Telegram Login Widget to obtain fresh `auth_date` and `hash` values. This error is typically handled by guiding the user to try logging in again.
Warnings
- gotcha The Telegram bot used for authentication must be correctly configured with a domain via the @BotFather bot using the `/setdomain` command. Failure to do so will prevent the Telegram Login Widget from functioning correctly or lead to verification failures.
- gotcha The `botToken` passed to the `telegram` plugin on the server-side is crucial for verifying the authenticity of Telegram login data. Ensure this token is securely stored (e.g., in environment variables) and is valid. An invalid or missing token will lead to authentication failures.
- gotcha As this package is currently in version `0.0.x`, its API surface may undergo breaking changes without a major version increment (e.g., 1.0.0). Developers should be aware of potential API instability and review changelogs for updates.
- gotcha This package, and its peer dependency `better-auth`, require Node.js version 20 or higher. Running on older Node.js versions will result in runtime errors related to unsupported syntax or APIs.
Install
-
npm install telegram-better-auth -
yarn add telegram-better-auth -
pnpm add telegram-better-auth
Imports
- telegram
const { telegram } = require('telegram-better-auth');import { telegram } from 'telegram-better-auth'; - telegramClient
const { telegramClient } = require('telegram-better-auth');import { telegramClient } from 'telegram-better-auth';
Quickstart
import { betterAuth } from 'better-auth';
import { createAuthClient } from 'better-auth/client';
import { telegram, telegramClient } from 'telegram-better-auth';
// --- Server-side configuration (auth.ts) ---
export const auth = betterAuth({
plugins: [
telegram({
botToken: process.env.TELEGRAM_BOT_TOKEN ?? '', // Ensure BOT_TOKEN is set in your environment
getTempEmail: (id) => `${id}@t.me`, // Function to generate a temporary email for Telegram users
}),
],
});
// --- Client-side configuration (auth-client.ts) ---
const authClient = createAuthClient({
plugins: [telegramClient()],
});
interface TelegramUserAuthData {
id: number;
first_name: string;
last_name?: string;
username?: string;
photo_url?: string;
auth_date: number;
hash: string;
}
// Example function to handle data from Telegram Login Widget callback
const onTelegramAuth = async (user: TelegramUserAuthData) => {
try {
console.log('Attempting Telegram sign-in for user:', user.username || user.id);
const data = await authClient.signIn.telegram(user);
console.log('Telegram sign-in successful:', data);
// Implement session refetch, redirect, etc.
} catch (error) {
console.error('Telegram sign-in failed:', error);
// Handle error (e.g., display message to user)
}
};
// This function would typically be called from the Telegram Login Widget's callback
// For demonstration, a placeholder:
// For testing, mock a user object (replace with actual data from Telegram):
// const mockTelegramUser: TelegramUserAuthData = {
// id: 123456789,
// first_name: 'Test',
// username: 'testuser',
// auth_date: Math.floor(Date.now() / 1000),
// hash: 'mockhash_for_dev_only' // This hash must be generated by Telegram, don't hardcode in production
// };
// onTelegramAuth(mockTelegramUser);