### Start Development Server
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth/README.md
Start the Next.js development server.
```sh
pnpm run dev
```
--------------------------------
### Navigate to Example Directory
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/remix-basic/README.md
Change the current directory to the remix-basic example folder.
```sh
cd examples/remix-basic
```
--------------------------------
### Navigate to Example Folder
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth-app-router/README.md
Change directory to the specific NextAuth.js App Router example.
```sh
cd examples/next-auth-app-router
```
--------------------------------
### Install and Build Dependencies
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth/README.md
Install and build project dependencies using pnpm.
```sh
pnpm install
pnpm kick-off
```
--------------------------------
### Navigate to NextAuth.js Example
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth/README.md
Change directory to the examples/next-auth folder.
```sh
cd examples/next-auth
```
--------------------------------
### Complete LoginButton Configuration Example
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
A comprehensive example demonstrating the LoginButton component with multiple configuration options for a typical authentication page.
```typescript
import { LoginButton, TelegramAuthData } from '@telegram-auth/react';
function AuthPage() {
const handleAuth = async (data: TelegramAuthData) => {
const response = await fetch('/api/auth/validate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
const result = await response.json();
if (result.success) {
window.location.href = '/dashboard';
}
};
return (
);
}
```
--------------------------------
### Package Installation
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Commands to install the @telegram-auth/server package using different package managers.
```bash
npm install @telegram-auth/server
# or
yarn add @telegram-auth/server
# or
pnpm add @telegram-auth/server
```
--------------------------------
### Install @telegram-auth/server
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/packages/server/README.md
Install the package using npm, yarn, or pnpm.
```sh
# npm
npm install @telegram-auth/server
# yarn
yarn add @telegram-auth/server
# with pnpm
pnpm add @telegram-auth/server
```
--------------------------------
### Install @telegram-auth/react
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/packages/react/README.md
Install the package using npm, yarn, or pnpm.
```sh
# npm
npm install @telegram-auth/react
# yarn
yarn add @telegram-auth/react
# with pnpm
pnpm add @telegram-auth/react
```
--------------------------------
### Basic Example with Callback
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/LoginButton.md
Demonstrates how to use the LoginButton component with a callback function to handle authentication data.
```APIDOC
```typescript
import { LoginButton, TelegramAuthData } from '@telegram-auth/react';
function LoginPage() {
const handleAuth = (data: TelegramAuthData) => {
console.log('User authenticated:', data);
// Send data to your server for validation
fetch('/api/auth/telegram', {
method: 'POST',
body: JSON.stringify(data),
});
};
return (
);
}
```
```
--------------------------------
### SubtleCrypto Implementation Examples
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/errors.md
Provides examples of how to configure the `subtleCrypto` option for different JavaScript environments, including Node.js, browsers, and CloudFlare Workers.
```typescript
// Node.js
import crypto from 'crypto';
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
subtleCrypto: crypto.webcrypto.subtle,
});
```
```typescript
// Browser / Web Worker
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
subtleCrypto: crypto.subtle, // Already available globally
});
```
```typescript
// CloudFlare Workers / Miniflare
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
// crypto.subtle is available in CF Workers
});
```
--------------------------------
### Install Telegram Auth Packages
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Installs the React and Server packages for Telegram authentication using npm.
```bash
npm install @telegram-auth/react @telegram-auth/server
```
--------------------------------
### Clone Repository
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth/README.md
Clone the telegram-auth repository to get started.
```sh
git clone https://github.com/manzoorwanijk/telegram-auth.git
cd telegram-auth
```
--------------------------------
### Example with Server-side Callback URL
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/LoginButton.md
Shows how to configure the LoginButton to send authentication data directly to a server-side URL.
```APIDOC
```typescript
```
```
--------------------------------
### Example with Custom Styling
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/LoginButton.md
Illustrates how to customize the appearance of the Telegram login button using available props.
```APIDOC
```typescript
```
```
--------------------------------
### LoginButton Component Usage
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Example of how to use the LoginButton component with various props. Ensure the botUsername is provided.
```typescript
{}}
buttonSize="large"
cornerRadius={8}
lang="en"
showAvatar={true}
requestAccess="write"
widgetVersion={21}
/>
```
--------------------------------
### AuthDataValidator Initialization Examples
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/AuthDataValidator.md
Demonstrates different ways to initialize the AuthDataValidator. You can provide all options during construction or set the bot token after initialization.
```typescript
import { AuthDataValidator } from '@telegram-auth/server';
// Basic initialization
const validator = new AuthDataValidator({
botToken: 'YOUR_BOT_TOKEN_HERE',
});
```
```typescript
// With custom options
const validator = new AuthDataValidator({
botToken: 'YOUR_BOT_TOKEN_HERE',
inValidateDataAfter: 3600, // 1 hour
throwIfEmptyData: true,
});
```
```typescript
// Initialize without token (set later)
const validator = new AuthDataValidator();
validator.setBotToken('YOUR_BOT_TOKEN_HERE');
```
--------------------------------
### createScript Function
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/README.md
Documentation for the createScript function, including its signature, parameters, return type, and usage examples.
```APIDOC
## createScript Function
### Description
A utility function to dynamically create and manage script tags, often used for integrating third-party scripts. It details the function signature, parameter table, return type, and provides multiple usage scenarios.
### Parameters
- **src** (string) - Required - The source URL of the script.
- **attributes** (object) - Optional - An object containing attributes to set on the script tag.
### Return Type
- **HTMLScriptElement** - The created script element.
### Usage
Includes examples for different frameworks and details on script attribute configuration, method chaining, and lifecycle management.
```
--------------------------------
### Load Bot Token from .env File
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Use this method when managing environment variables in a .env file. Requires the dotenv package to be installed and configured.
```bash
# .env
TELEGRAM_BOT_TOKEN=1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef
```
```typescript
import dotenv from 'dotenv';
dotenv.config();
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
});
```
--------------------------------
### LoginButton React Component
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/README.md
Documentation for the LoginButton React component, detailing its props, return type, and usage examples.
```APIDOC
## LoginButton React Component
### Description
A React component that renders a button for initiating Telegram login. It includes a comprehensive props table, return type description, and various usage examples.
### Props
- **botId** (string) - Required - The ID of your Telegram bot.
- **redirectUrl** (string) - Optional - The URL to redirect to after successful authentication.
- **buttonStyle** (object) - Optional - Custom styles for the button.
### Usage
Examples cover basic usage, server callback handling, and custom styling. Best practices, widget caching, and lifecycle notes are also included.
```
--------------------------------
### Minimal AuthDataValidator Configuration
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Demonstrates the most basic setup for AuthDataValidator, requiring only the bot token. Ensure the bot token is valid and obtained from BotFather.
```typescript
import { AuthDataValidator } from '@telegram-auth/server';
// Minimal configuration
const validator = new AuthDataValidator({
botToken: 'YOUR_BOT_TOKEN',
});
```
--------------------------------
### Express.js Backend Authentication
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Example of setting up a Telegram authentication endpoint using Express.js and the AuthDataValidator. Requires setting the TELEGRAM_BOT_TOKEN environment variable.
```typescript
import { AuthDataValidator, objectToAuthDataMap } from '@telegram-auth/server';
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
});
app.post('/api/auth/telegram', async (req, res) => {
try {
const user = await validator.validate(objectToAuthDataMap(req.body));
req.session.userId = user.id;
res.json({ success: true });
} catch (error) {
res.status(401).json({ error: 'Authentication failed' });
}
});
```
--------------------------------
### Complete Conversion and Validation Example
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/utility-functions.md
Demonstrates how to use utility functions to convert authentication data from different sources (Express.js request body, URL string, browser search parameters) and validate it using the AuthDataValidator. Ensure the TELEGRAM_BOT_TOKEN environment variable is set.
```typescript
import {
AuthDataValidator,
objectToAuthDataMap,
searchParamsToAuthDataMap,
urlStrToAuthDataMap,
} from '@telegram-auth/server';
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
});
// Method 1: From Express.js request body
app.post('/auth', async (req, res) => {
const authData = objectToAuthDataMap(req.body);
const user = await validator.validate(authData);
res.json(user);
});
// Method 2: From URL search parameters
const handleCallback = async (url: string) => {
const authData = urlStrToAuthDataMap(url);
const user = await validator.validate(authData);
return user;
};
// Method 3: From query string in browser
const validateFromURL = async () => {
const params = new URLSearchParams(window.location.search);
const authData = searchParamsToAuthDataMap(params);
const user = await validator.validate(authData);
return user;
};
```
--------------------------------
### LoginButton Component Usage
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/types.md
Example of how to use the LoginButton component in a React application. Ensure either authCallbackUrl or onAuthCallback is provided.
```typescript
import { LoginButton } from '@telegram-auth/react';
console.log(data)}
requestAccess="write"
showAvatar={true}
/>
```
--------------------------------
### Examples Triggering Incomplete Data Error
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/errors.md
Demonstrates various scenarios where 'Invalid! Incomplete data provided.' error is triggered due to missing required fields in the authentication data.
```typescript
import { AuthDataValidator, objectToAuthDataMap } from '@telegram-auth/server';
const validator = new AuthDataValidator({ botToken: 'token' });
// Missing hash
await validator.validate(objectToAuthDataMap({ id: 123, auth_date: 1234567890 }));
// Error: "Invalid! Incomplete data provided."
// Missing auth_date
await validator.validate(objectToAuthDataMap({ id: 123, hash: 'abc123' }));
// Error: "Invalid! Incomplete data provided."
// Missing id and user
await validator.validate(objectToAuthDataMap({ hash: 'abc123', auth_date: 1234567890 }));
// Error: "Invalid! Incomplete data provided."
// Empty object
await validator.validate(objectToAuthDataMap({}));
// Error: "Invalid! Incomplete data provided."
```
--------------------------------
### Configure Environment Variables
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/remix-basic/README.md
Create a .env file by copying the .example.env and update BOT_TOKEN and BOT_USERNAME with your Telegram bot's credentials.
```sh
cp .example.env .env
# Update BOT_TOKEN and BOT_USERNAME in .env file
```
--------------------------------
### Package Structure Overview
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Illustrates the directory structure of the @telegram-auth/ monorepo, highlighting the 'react' and 'server' packages and their key exports.
```tree
@telegram-auth/
├── react/
│ ├── LoginButton (Component)
│ ├── createScript (Function)
│ └── Types (TelegramAuthData, LoginButtonProps, etc.)
│
└── server/
├── AuthDataValidator (Class)
├── Utilities (Data conversion functions)
├── Types (AuthDataMap, TelegramUserData)
└── Utils subexport (@telegram-auth/server/utils)
```
--------------------------------
### AuthDataValidator Class
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/README.md
Documentation for the AuthDataValidator class, covering its constructor, public methods, and usage examples in various frameworks.
```APIDOC
## AuthDataValidator Class
### Description
Provides functionality to validate Telegram authentication data. This class includes a constructor with options, all public methods with signatures, parameter tables, return types, and chaining examples.
### Usage
Examples are provided for Express.js, Next.js, and Web Workers. Cryptographic implementation details, related types, and security considerations are also discussed.
### Constructor
- **options** (AuthDataValidatorOptions) - Required - Configuration options for the validator.
```
--------------------------------
### Expose Local Server with ngrok
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth/README.md
Use ngrok to expose your local server to the internet and update NEXTAUTH_URL.
```sh
ngrok http 3000
```
--------------------------------
### Configure Environment Variables
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth-app-router/README.md
Create and update the .env.local file with your Telegram Bot Token and Username obtained from BotFather.
```sh
cp .example.env.local .env.local
# Update BOT_TOKEN and BOT_USERNAME in .env.local
```
--------------------------------
### Configure LoginButton Component
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/00-START-HERE.md
Set up the LoginButton component with your bot username and optional props for button appearance, language, and authentication callback.
```typescript
```
--------------------------------
### Build NPM Scripts
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Scripts for building the package in different formats (ESM, CJS) and generating documentation.
```bash
# Build
npm run build # Build ESM and CJS
npm run build:ts # TypeScript compilation
npm run build:esm # ES modules output
npm run build:cjs # CommonJS output
npm run build:docs # Generate TypeDoc documentation
```
--------------------------------
### NPM Scripts for @telegram-auth/react
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Lists common NPM scripts for building, developing, testing, and maintaining the @telegram-auth/react package.
```bash
# Build
npm run build # Build ESM and CJS
npm run build:ts # TypeScript compilation
npm run build:esm # ES modules output
npm run build:cjs # CommonJS output
npm run build:docs # Generate TypeDoc documentation
# Development
npm run dev # Watch mode TypeScript compilation
npm run typecheck # Type checking without emit
# Testing
npm run test # Run Jest tests
npm run test:watch # Watch mode testing
# Maintenance
npm run clean # Remove build artifacts
npm run lint # Lint code
```
--------------------------------
### Configure Bot Domain with BotFather
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/examples/next-auth-app-router/README.md
After obtaining the ngrok URL, use the /setdomain command with BotFather to set your bot's domain and avoid 'Bot domain invalid' errors.
```sh
# Send /setdomain command to @BotFather with the ngrok URL
```
--------------------------------
### Instantiate AuthDataValidator
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/types.md
Example of creating an AuthDataValidator instance with custom options. Set `inValidateDataAfter` to 1 hour and disable throwing errors for incomplete data.
```typescript
import { AuthDataValidator } from '@telegram-auth/server';
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
inValidateDataAfter: 3600, // 1 hour
throwIfEmptyData: false, // Return data even if incomplete
});
```
--------------------------------
### Validating Auth Data from Request Body
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/utility-functions.md
This example shows how to use `objectToAuthDataMap` to convert the request body (commonly from Express.js or Next.js) into an AuthDataMap and then validate it.
```APIDOC
## POST /auth
### Description
Validates Telegram authentication data received in the request body.
### Method
POST
### Endpoint
/auth
### Parameters
#### Request Body
- **authData** (AuthDataMap) - Required - The authentication data map derived from the request body.
### Request Example
```json
{
"id": 123456789,
"first_name": "John",
"username": "john_doe",
"photo_url": "...",
"auth_date": 1678886400,
"hash": "..."
}
```
### Response
#### Success Response (200)
- **user** (TelegramUserData) - The validated Telegram user data.
#### Response Example
```json
{
"id": 123456789,
"first_name": "John",
"username": "john_doe",
"photo_url": "..."
}
```
```
--------------------------------
### AuthDataValidator Initialization and Chaining
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Demonstrates initializing the AuthDataValidator with options and using its chainable setters for configuration. The botToken is a required parameter for initialization.
```typescript
const validator = new AuthDataValidator({
botToken: 'bot_token',
inValidateDataAfter: 86400,
throwIfEmptyData: true,
});
// Chainable setters
validator
.setBotToken('token')
.setInValidateDataAfter(3600)
.setThrowIfEmptyData(false);
```
--------------------------------
### Next.js API Route Authentication
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Example of implementing Telegram authentication within a Next.js API route using AuthDataValidator. Ensure TELEGRAM_BOT_TOKEN is set in your environment.
```typescript
import { AuthDataValidator, objectToAuthDataMap } from '@telegram-auth/server';
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
});
export default async function handler(req, res) {
try {
const user = await validator.validate(objectToAuthDataMap(req.query));
res.status(200).json({ user });
} catch (error) {
res.status(401).json({ error: error.message });
}
}
```
--------------------------------
### React Package Components and Utilities
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Documentation for the React package, including the LoginButton component and the createScript utility function.
```APIDOC
## LoginButton
### Description
A React component that renders a button for Telegram login.
### Props
- **props** (LoginButtonProps) - Required - Properties for the LoginButton component.
### Type
function LoginButton(props: LoginButtonProps): React.ReactElement
```
```APIDOC
## createScript
### Description
Utility function to create a script element for Telegram authentication.
### Parameters
- **options** (CreateScriptOptions) - Required - Options for creating the script.
### Returns
- HTMLScriptElement - The created script element.
### Type
function createScript(options: CreateScriptOptions): HTMLScriptElement
```
--------------------------------
### Load Bot Token from Environment Variable
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Recommended method for loading the bot token. Ensure the TELEGRAM_BOT_TOKEN environment variable is set.
```typescript
// Recommended: use environment variables
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
});
```
--------------------------------
### Server Package Conversion Utilities
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Signatures for conversion utility functions in the Server package.
```typescript
// Conversion utilities
function searchParamsToAuthDataMap(searchParams: URLSearchParams): AuthDataMap
```
```typescript
function objectToAuthDataMap(data: Record): AuthDataMap
```
```typescript
function urlStrToAuthDataMap(urlStr: string): AuthDataMap
```
```typescript
function hexStringToArrayBuffer(hexString: string): Uint8Array
```
--------------------------------
### Server-side Validation with @telegram-auth/server
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/packages/react/README.md
Validate Telegram authentication data on the server-side using the `AuthDataValidator` from `@telegram-auth/server`. This example demonstrates parsing URL query parameters and validating the data against your bot token.
```ts
import { AuthDataValidator } from '@telegram-auth/server';
import { urlStrToAuthDataMap } from '@telegram-auth/server/utils';
const validator = new AuthDataValidator({ botToken: process.env.BOT_TOKEN });
const data = urlStrToAuthDataMap(request.url);
try {
const user = await validator.validate(data);
// The data is now valid and you can sign in the user.
console.log(user);
} catch (error) {
console.error(error);
}
```
--------------------------------
### Add Login Button to React App
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/00-START-HERE.md
Use the LoginButton component from '@telegram-auth/react' to initiate the Telegram login flow. Ensure you have React 18+ installed. The onAuthCallback function will receive the authentication data.
```javascript
import { LoginButton } from '@telegram-auth/react';
function App() {
const handleAuth = (data) => {
console.log('Authentication data:', data);
// Send data to your server for validation
};
return (
);
}
```
--------------------------------
### Web Worker for Telegram Authentication Validation
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Example of performing Telegram authentication validation within a Web Worker using AuthDataValidator and searchParamsToAuthDataMap. The worker expects botToken and searchParams in its event data.
```typescript
import { AuthDataValidator, searchParamsToAuthDataMap } from '@telegram-auth/server';
self.addEventListener('message', async (event) => {
const validator = new AuthDataValidator({
botToken: event.data.botToken,
});
try {
const user = await validator.validate(
searchParamsToAuthDataMap(new URLSearchParams(event.data.searchParams))
);
self.postMessage({ success: true, user });
} catch (error) {
self.postMessage({ success: false, error: error.message });
}
});
```
--------------------------------
### Server Package - Conversion Utilities
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Utility functions for converting various data formats into AuthDataMap.
```APIDOC
## searchParamsToAuthDataMap
### Description
Converts URLSearchParams to an AuthDataMap.
### Parameters
- **searchParams** (URLSearchParams) - Required - The URLSearchParams to convert.
### Returns
- AuthDataMap - The resulting authentication data map.
### Type
function searchParamsToAuthDataMap(searchParams: URLSearchParams): AuthDataMap
```
```APIDOC
## objectToAuthDataMap
### Description
Converts a generic object to an AuthDataMap.
### Parameters
- **data** (Record) - Required - The object to convert.
### Returns
- AuthDataMap - The resulting authentication data map.
### Type
function objectToAuthDataMap(data: Record): AuthDataMap
```
```APIDOC
## urlStrToAuthDataMap
### Description
Converts a URL string to an AuthDataMap.
### Parameters
- **urlStr** (string) - Required - The URL string to convert.
### Returns
- AuthDataMap - The resulting authentication data map.
### Type
function urlStrToAuthDataMap(urlStr: string): AuthDataMap
```
```APIDOC
## hexStringToArrayBuffer
### Description
Converts a hexadecimal string to a Uint8Array (ArrayBuffer).
### Parameters
- **hexString** (string) - Required - The hexadecimal string to convert.
### Returns
- Uint8Array - The resulting ArrayBuffer.
### Type
function hexStringToArrayBuffer(hexString: string): Uint8Array
```
--------------------------------
### React Package Entry Point
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Exports components, functions, and types from the React package.
```typescript
// packages/react/src/index.ts
export * from './LoginButton';
export * from './createScript';
export * from './types';
```
--------------------------------
### Web Worker (Browser) with AuthDataValidator
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/AuthDataValidator.md
Implement Telegram authentication validation within a Web Worker in the browser. This example shows how to receive search parameters and the bot token from the main thread and post back the validation result.
```typescript
import { AuthDataValidator, searchParamsToAuthDataMap } from '@telegram-auth/server';
self.addEventListener('message', async (event) => {
const { searchParams } = event.data;
const validator = new AuthDataValidator({
botToken: event.data.botToken,
});
try {
const user = await validator.validate(
searchParamsToAuthDataMap(new URLSearchParams(searchParams))
);
self.postMessage({ success: true, user });
} catch (error) {
self.postMessage({ success: false, error: error.message });
}
});
```
--------------------------------
### LoginButton Callback Configuration
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Configure how the LoginButton handles authentication callbacks, either client-side or server-side.
```typescript
// Client-side callback
{
console.log('Authenticated as:', data.first_name);
// Send data to server
fetch('/api/auth', { method: 'POST', body: JSON.stringify(data) });
}}
/>
```
```typescript
// Server-side callback
```
--------------------------------
### Package.json Exports Configuration
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Defines how the package's entry points are exposed for different module systems (ES modules and CommonJS).
```json
{
"exports": {
".": {
"import": "./dist/esm/index.js",
"require": "./dist/cjs/index.js"
},
"./package.json": "./package.json"
},
"types": "./dist/cjs/index.d.ts"
}
```
--------------------------------
### Export Server Entry Points
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Exports all necessary components from the server package, including the validator and utility functions.
```typescript
// packages/server/src/index.ts
export * from './AuthDataValidator';
export * from './utils';
```
--------------------------------
### Basic LoginButton Usage with Callback
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/LoginButton.md
Demonstrates the basic usage of the LoginButton component with a custom authentication callback function. This is useful when you want to handle the authentication data directly within your React application.
```typescript
import { LoginButton, TelegramAuthData } from '@telegram-auth/react';
function LoginPage() {
const handleAuth = (data: TelegramAuthData) => {
console.log('User authenticated:', data);
// Send data to your server for validation
fetch('/api/auth/telegram', {
method: 'POST',
body: JSON.stringify(data),
});
};
return (
);
}
```
--------------------------------
### Configure Strict Authentication
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Set the STRICT_AUTH environment variable to true or false to enable or disable strict authentication. Defaults to true.
```bash
STRICT_AUTH=true
```
--------------------------------
### Import Server Utils
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Imports utility functions and types from the '@telegram-auth/server/utils' module.
```typescript
// @telegram-auth/server/utils
import {
searchParamsToAuthDataMap,
objectToAuthDataMap,
urlStrToAuthDataMap,
hexStringToArrayBuffer,
AuthDataMap,
TelegramUserData
} from '@telegram-auth/server/utils';
```
--------------------------------
### React Frontend Implementation
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Implements a login page using the LoginButton component from @telegram-auth/react. Handles the authentication callback by sending data to a backend API.
```typescript
import { LoginButton, TelegramAuthData } from '@telegram-auth/react';
function LoginPage() {
const handleAuth = async (data: TelegramAuthData) => {
await fetch('/api/auth/validate', {
method: 'POST',
body: JSON.stringify(data),
});
};
return ;
}
```
--------------------------------
### Configure Auth Callback Function for LoginButton
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Provide the onAuthCallback prop with a function to be executed upon successful authentication.
```javascript
onAuthCallback: function
```
--------------------------------
### Create Script with onAuthCallback
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/createScript.md
Creates a script element with a specified bot username and an authentication callback function. The callback is invoked with authentication data. The script element needs to be appended to a specific DOM element.
```typescript
const script = createScript({
botUsername: 'my_bot',
onAuthCallback: (data) => {
console.log('Auth data:', data);
},
buttonSize: 'medium',
lang: 'en',
});
document.getElementById('login-container').appendChild(script);
```
--------------------------------
### LoginButton with Server-side Callback URL
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/LoginButton.md
Shows how to configure the LoginButton to send authentication data to a server-side URL. This is useful for offloading authentication logic to your backend.
```typescript
```
--------------------------------
### Create Script with authCallbackUrl
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/createScript.md
Generates a script element configured with a bot username and an authentication callback URL. This URL will receive the authentication data. The script element needs to be appended to the DOM.
```typescript
const script = createScript({
botUsername: 'my_bot',
authCallbackUrl: 'https://example.com/api/auth/telegram',
buttonSize: 'small',
cornerRadius: 8,
widgetVersion: 21,
});
document.body.appendChild(script);
```
--------------------------------
### Configure Button Size for LoginButton
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Set the buttonSize prop to control the visual size of the Telegram Login button. Defaults to 'large'.
```javascript
buttonSize: 'large'
```
--------------------------------
### LoginButton Permissions Configuration
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Configure the access permissions requested by the LoginButton. Can request write access or no permissions.
```typescript
// Request write access (default)
```
```typescript
// No permissions request
```
--------------------------------
### LoginButton Size Options
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Set the size of the LoginButton component. Recommended for different layout contexts.
```typescript
// Large button (recommended for login pages)
```
```typescript
// Medium button (standard size)
```
```typescript
// Small button (for sidebars/compact layouts)
```
--------------------------------
### Import All From @telegram-auth/server
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Import statement for all exports from the @telegram-auth/server package.
```typescript
import {
AuthDataValidator,
searchParamsToAuthDataMap,
objectToAuthDataMap,
urlStrToAuthDataMap,
hexStringToArrayBuffer,
AuthDataMap,
TelegramUserData,
AuthDataValidatorOptions
} from '@telegram-auth/server';
```
--------------------------------
### Development NPM Scripts
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Scripts for development, including watch mode compilation and type checking.
```bash
# Development
npm run dev # Watch mode TypeScript compilation
npm run typecheck # Type checking without emit
```
--------------------------------
### Set Telegram Bot Token Environment Variable
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Configures the necessary Telegram Bot Token from BotFather as an environment variable for backend authentication.
```bash
# .env
TELEGRAM_BOT_TOKEN=your_bot_token_from_botfather
```
--------------------------------
### React LoginButton Component Configuration
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Configure the LoginButton component with various props for bot username, callback, UI, and permissions. Choose between client-side or server-side callbacks.
```typescript
import { LoginButton } from '@telegram-auth/react';
console.log(data)}
// OR
authCallbackUrl="https://yourdomain.com/api/auth"
// UI Configuration
buttonSize="large" // 'large' | 'medium' | 'small'
cornerRadius={8} // pixels
lang="en" // BCP 47 language tag
showAvatar={true} // boolean
// Permissions
requestAccess="write" // 'write' | null
// Cache busting
widgetVersion={21} // number | string
/>
```
--------------------------------
### CreateScriptOptions
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/types.md
Options for creating the Telegram widget script element. This type extends LoginButtonProps with no additional fields and is used internally by the LoginButton component, but can also be used standalone.
```APIDOC
## CreateScriptOptions
### Description
Options for creating the Telegram widget script element. This type extends `LoginButtonProps` with no additional fields.
### Fields
Same as `LoginButtonProps`.
### Module
`@telegram-auth/react`
### Usage
```typescript
import { createScript } from '@telegram-auth/react';
const script = createScript({
botUsername: 'mybot',
buttonSize: 'small',
lang: 'fr',
});
document.body.appendChild(script);
```
### Notes
- This type extends `LoginButtonProps` with no additional fields.
- Used internally by the `LoginButton` component.
- Can be used standalone to manually create and manage the widget script.
```
--------------------------------
### createScript Function
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/packages/react/docs/README.md
Creates a script tag with the necessary attributes to load the Telegram widget. It takes CreateScriptOptions as input.
```APIDOC
## createScript
### Description
It creates a script tag with the right attributes to load the Telegram widget.
### Parameters
- `options` (CreateScriptOptions) - The options to create the script.
### Returns
HTMLScriptElement - A script element.
### See
https://core.telegram.org/widgets/login
```
--------------------------------
### React Package Component and Utilities
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Reference for the LoginButton component and createScript utility function in the React package.
```typescript
// Component
function LoginButton(props: LoginButtonProps): React.ReactElement
```
```typescript
// Utilities
function createScript(options: CreateScriptOptions): HTMLScriptElement
```
--------------------------------
### Provide SubtleCrypto for Node.js
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/errors.md
Shows how to explicitly provide the `SubtleCrypto` API for Node.js environments to avoid the 'Error! Subtle crypto is needed for validation.' error. This ensures cryptographic operations are available.
```typescript
import { AuthDataValidator } from '@telegram-auth/server';
import crypto from 'crypto';
try {
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
// Explicitly provide crypto for Node.js
subtleCrypto: crypto.webcrypto.subtle,
});
} catch (error) {
if (error.message === 'Error! Subtle crypto is needed for validation.') {
console.error('Crypto API not available');
process.exit(1);
}
}
```
--------------------------------
### Configure Avatar Visibility for LoginButton
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Set the showAvatar prop to true to display the user's photo on the Telegram Login button. Defaults to true.
```javascript
showAvatar: true
```
--------------------------------
### Basic Usage of AuthDataValidator
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Demonstrates initializing the AuthDataValidator and validating user data from request query parameters. Ensure the TELEGRAM_BOT_TOKEN environment variable is set.
```typescript
import { AuthDataValidator, objectToAuthDataMap } from '@telegram-auth/server';
const validator = new AuthDataValidator({
botToken: process.env.TELEGRAM_BOT_TOKEN,
});
const user = await validator.validate(objectToAuthDataMap(req.query));
console.log(`Authenticated as: ${user.first_name}`);
```
--------------------------------
### Testing NPM Scripts
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/packages-overview.md
Scripts for running tests in various environments like Node.js and Cloudflare Workers.
```bash
# Testing
npm run test # Run tests in Node.js and Cloudflare environments
npm run test:node # Jest tests in Node.js environment
npm run test:cf # Tests in Cloudflare Workers environment (Miniflare)
npm run test:watch # Watch mode testing
```
--------------------------------
### CreateScriptOptions Properties
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/packages/react/docs/interfaces/CreateScriptOptions.md
This interface defines the properties that can be passed to configure the Telegram authentication script, including bot username, callback URL, button appearance, and access requests.
```APIDOC
## Interface: CreateScriptOptions
The options to create the script.
### Properties
- **botUsername** (`string`): The username of the bot that will be used to authenticate the user.
- **authCallbackUrl** (`string`, optional): The URL where the auth data from Telegram will be sent.
- **buttonSize** (`'large' | 'medium' | 'small'`, optional, default: `'large'`): The size of the button.
- **cornerRadius** (`number`, optional): The radius of the button corners.
- **lang** (`string`, optional, default: `'en'`): The language of the button.
- **onAuthCallback** (`(data: TelegramAuthData) => void`, optional): The callback function that will be called when the user is authenticated.
- **requestAccess** (`null | 'write'`, optional, default: `'write'`): The access level that the bot will request.
- **showAvatar** (`boolean`, optional, default: `true`): Whether to show the user's avatar.
- **widgetVersion** (`string | number`, optional): The version of the Telegram widget to deal with browser caching.
```
--------------------------------
### Create Script with Custom Options
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/api-reference/createScript.md
Creates a script element with various custom options, including button size, corner radius, language, avatar display, access request, and widget version. The script element must be appended to a specified container element.
```typescript
const script = createScript({
botUsername: 'my_bot',
buttonSize: 'large',
cornerRadius: 15,
lang: 'ru',
showAvatar: true,
requestAccess: 'write',
widgetVersion: '21',
});
const container = document.getElementById('login');
container.appendChild(script);
```
--------------------------------
### Configure Access Request for LoginButton
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Set the requestAccess prop to define the level of access the button requests. Defaults to 'write'.
```javascript
requestAccess: 'write'
```
--------------------------------
### Export Server Utils Index
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Exports utility functions from the server package's utils directory.
```typescript
// packages/server/src/utils/index.ts
export * from './hexStringToArrayBuffer';
export * from './searchParamsToAuthDataMap';
export * from './objectToAuthDataMap';
export * from './urlStrToAuthDataMap';
export * from './types';
```
--------------------------------
### Configure Language for LoginButton
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Set the lang prop to specify the language of the Telegram Login button. Defaults to 'en'.
```javascript
lang: 'en'
```
--------------------------------
### Initialize AuthDataValidator
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/00-START-HERE.md
Configure the AuthDataValidator with your bot token and optional settings for data validation timing and error handling.
```typescript
new AuthDataValidator({
botToken: 'token',
// Required
inValidateDataAfter: 86400, // 1 day (seconds)
throwIfEmptyData: true, // Throw on incomplete data
})
```
--------------------------------
### Utility Functions
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
A collection of utility functions for converting and processing authentication data from various sources.
```APIDOC
## Utility Functions
### `searchParamsToAuthDataMap(searchParams: URLSearchParams): AuthDataMap`
Converts URL search parameters into an AuthDataMap.
### `objectToAuthDataMap(obj: Record): AuthDataMap`
Converts a plain JavaScript object into an AuthDataMap.
### `urlStrToAuthDataMap(urlStr: string): AuthDataMap`
Converts a URL string into an AuthDataMap.
### `hexStringToArrayBuffer(hexString: string): ArrayBuffer`
Converts a hexadecimal string representation into an ArrayBuffer.
```
--------------------------------
### Configure Auth Expiry Time
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/INDEX.md
Set the AUTH_EXPIRY_SECONDS environment variable to configure the authentication data expiration time in seconds. Defaults to 1 day.
```bash
AUTH_EXPIRY_SECONDS=86400
```
--------------------------------
### LoginButton Language Configuration
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/configuration.md
Configure the display language for the LoginButton. Supports various language codes.
```typescript
// English
```
```typescript
// Russian
```
```typescript
// French
```
```typescript
// German
```
```typescript
// Spanish
```
```typescript
// Italian
```
```typescript
// Portuguese (Brazilian)
```
```typescript
// Chinese (Simplified)
```
```typescript
// See Telegram's documentation for all supported language codes
```
--------------------------------
### Create Telegram Widget Script
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/types.md
Manually create and append the Telegram login widget script to the document body. This is useful for standalone widget management.
```typescript
import { createScript } from '@telegram-auth/react';
const script = createScript({
botUsername: 'mybot',
buttonSize: 'small',
lang: 'fr',
});
document.body.appendChild(script);
```
--------------------------------
### Import All From @telegram-auth/react
Source: https://github.com/manzoorwanijk/telegram-auth/blob/main/_autodocs/SYMBOL-INDEX.md
Import statement for all exports from the @telegram-auth/react package.
```typescript
import {
LoginButton,
createScript,
TelegramAuthData,
LoginButtonProps,
CreateScriptOptions
} from '@telegram-auth/react';
```