# 3xui-api-client ## Introduction The 3xui-api-client is a comprehensive Node.js library designed to interact with 3x-ui panel APIs, providing seamless management of VPN proxy servers. This library simplifies the complex task of managing inbounds, clients, and traffic across multiple proxy protocols including VLESS, VMess, Trojan, Shadowsocks, and WireGuard. Built with production-grade features, it offers automatic session management, secure credential generation, and built-in input validation to ensure safe and reliable server operations. At its core, the library abstracts away the complexity of working with 3x-ui's REST API by providing intuitive methods for all common operations. It automatically handles authentication, session cookies, retry logic, and rate limiting, allowing developers to focus on building their applications rather than managing low-level API details. The library supports both simple use cases (basic client management) and advanced scenarios (web application integration with Redis/database session storage, bulk credential generation, and protocol-specific configurations). ## Authentication and Initialization Basic client initialization with automatic session management ```javascript require('dotenv').config(); const ThreeXUI = require('3xui-api-client'); // Initialize client - authentication happens automatically on first API call const client = new ThreeXUI( process.env.PANEL_URL, // e.g., 'https://your-server.com:2053' process.env.PANEL_USERNAME, // e.g., 'admin' process.env.PANEL_PASSWORD // your secure password ); // No manual login needed - just call any API method const inbounds = await client.getInbounds(); console.log('Connected successfully:', inbounds.success); // Output: Connected successfully: true ``` ## Advanced Session Management with Redis Configure persistent session storage for production web applications ```javascript const ThreeXUI = require('3xui-api-client'); const redis = require('redis'); // Create Redis client const redisClient = redis.createClient({ host: 'localhost', port: 6379 }); await redisClient.connect(); // Initialize with Redis session management const client = new ThreeXUI( 'https://your-server.com:2053', 'admin', 'password', { sessionManager: ThreeXUI.createSessionManager({ store: ThreeXUI.createRedisStore(redisClient, { keyPrefix: '3xui:session:' }), sessionTTL: 3600, // 1 hour autoRefresh: true, refreshThreshold: 300 // Refresh 5 minutes before expiry }), timeout: 30000, maxRequestsPerMinute: 60 } ); // Check session validity const isValid = await client.isSessionValid(); console.log('Session valid:', isValid); // Output: Session valid: true // Get session statistics const stats = await client.getSessionStats(); console.log('Active sessions:', stats); // Output: { activeSessions: 1, totalRequests: 15, lastActivity: '2025-11-30T10:00:00Z' } ``` ## Inbound Management - List All Inbounds Retrieve all configured inbound proxy servers ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); try { const response = await client.getInbounds(); if (response.success) { const inbounds = response.obj; console.log(`Total inbounds: ${inbounds.length}`); inbounds.forEach(inbound => { console.log(`ID: ${inbound.id}, Port: ${inbound.port}, Protocol: ${inbound.protocol}`); console.log(`Remark: ${inbound.remark}, Enabled: ${inbound.enable}`); }); } } catch (error) { console.error('Failed to get inbounds:', error.message); } // Output: // Total inbounds: 3 // ID: 1, Port: 443, Protocol: vless // Remark: Main VLESS Server, Enabled: true // ID: 2, Port: 8443, Protocol: vmess // Remark: VMess Server, Enabled: true ``` ## Inbound Management - Create New Inbound Add a new VLESS inbound with Reality protocol ```javascript const ThreeXUI = require('3xui-api-client'); const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); // Generate Reality keys for anti-censorship const realityKeys = client.generateRealityKeys(); const inboundConfig = { remark: "VLESS Reality Server", enable: true, port: 443, protocol: "vless", settings: JSON.stringify({ clients: [], decryption: "none", fallbacks: [] }), streamSettings: JSON.stringify({ network: "tcp", security: "reality", realitySettings: { show: false, dest: "www.google.com:443", xver: 0, serverNames: ["www.google.com"], privateKey: realityKeys.privateKey, publicKey: realityKeys.publicKey, shortIds: [""] }, tcpSettings: { acceptProxyProtocol: false, header: { type: "none" } } }), sniffing: JSON.stringify({ enabled: true, destOverride: ["http", "tls", "quic"] }) }; try { const result = await client.addInbound(inboundConfig); if (result.success) { console.log('Inbound created successfully!'); console.log('Inbound ID:', result.obj?.id); console.log('Reality Public Key:', realityKeys.publicKey); } } catch (error) { console.error('Failed to create inbound:', error.message); } // Output: // Inbound created successfully! // Inbound ID: 5 // Reality Public Key: kQvXf5qZLYOGvNk4NdT8Z3mP1A2bC7dE9fG0hI3jK4lM5 ``` ## Client Management - Add Client with Auto-Generated Credentials Simplify client creation with automatic credential generation ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); const inboundId = 1; // Your inbound ID try { // OLD WAY: 35+ lines of manual UUID generation, configuration, JSON.stringify() // NEW WAY: Single line with automatic secure credential generation const result = await client.addClientWithCredentials(inboundId, 'vless', { email: 'user@example.com', limitIp: 2, // Max 2 simultaneous connections totalGB: 50, // 50 GB traffic limit expiryTime: Date.now() + (30 * 24 * 60 * 60 * 1000), // 30 days flow: 'xtls-rprx-vision' // Optimal flow for Reality }); if (result.success) { console.log('Client created with credentials:'); console.log('UUID:', result.credentials.id); console.log('Email:', result.credentials.email); console.log('Flow:', result.credentials.flow); console.log('Encryption:', result.credentials.encryption); // Save these credentials for the client const clientCredentials = { uuid: result.credentials.id, email: result.credentials.email, inboundId: inboundId }; } } catch (error) { console.error('Failed to add client:', error.message); } // Output: // Client created with credentials: // UUID: 7f8e9d5c-4b3a-2e1f-0d9c-8b7a6e5d4c3b // Email: user@example.com // Flow: xtls-rprx-vision // Encryption: none ``` ## Client Management - Update Client Settings Modify existing client traffic limits and expiry ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); const clientId = '7f8e9d5c-4b3a-2e1f-0d9c-8b7a6e5d4c3b'; const inboundId = 1; try { const result = await client.updateClientWithCredentials(clientId, inboundId, { email: 'updated_user@example.com', limitIp: 3, // Increase to 3 connections totalGB: 100, // Increase to 100 GB expiryDays: 60, // Extend for 60 more days enable: true }); if (result.success) { console.log('Client updated successfully!'); console.log('Conversions:', result.conversions); console.log('Updated options:', result.updatedOptions); } } catch (error) { console.error('Failed to update client:', error.message); } // Output: // Client updated successfully! // Conversions: { totalGB: '100GB', expiryDays: '60 days → 2026-01-29T10:00:00Z' } // Updated options: { email: 'updated_user@example.com', limitIp: 3, ... } ``` ## Client Management - Delete Client Remove a client from an inbound ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); const inboundId = 1; const clientUUID = '7f8e9d5c-4b3a-2e1f-0d9c-8b7a6e5d4c3b'; try { const result = await client.deleteClient(inboundId, clientUUID); if (result.success) { console.log('Client deleted successfully'); console.log('Message:', result.msg); } } catch (error) { console.error('Failed to delete client:', error.message); } // Output: // Client deleted successfully // Message: Client removed from inbound ``` ## Traffic Management - Monitor Client Traffic Get detailed traffic statistics for a specific client ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); try { // Get traffic by email const traffic = await client.getClientTrafficsByEmail('user@example.com'); if (traffic.success) { const data = traffic.obj; const upMB = (data.up / 1024 / 1024).toFixed(2); const downMB = (data.down / 1024 / 1024).toFixed(2); const totalMB = ((data.up + data.down) / 1024 / 1024).toFixed(2); console.log(`Traffic for ${data.email}:`); console.log(`Upload: ${upMB} MB`); console.log(`Download: ${downMB} MB`); console.log(`Total: ${totalMB} MB`); console.log(`Enabled: ${data.enable}`); } // Alternative: Get traffic by UUID const trafficById = await client.getClientTrafficsById('7f8e9d5c-4b3a-2e1f-0d9c'); console.log('Traffic by ID:', trafficById.obj); } catch (error) { console.error('Failed to get traffic:', error.message); } // Output: // Traffic for user@example.com: // Upload: 145.67 MB // Download: 3421.89 MB // Total: 3567.56 MB // Enabled: true ``` ## Traffic Management - Reset Client Traffic Reset traffic counters for a specific client ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); const inboundId = 1; const clientEmail = 'user@example.com'; try { // Reset individual client traffic const result = await client.resetClientTraffic(inboundId, clientEmail); if (result.success) { console.log('Traffic reset successfully for', clientEmail); } // Reset all client traffic in an inbound const resetAll = await client.resetAllClientTraffics(inboundId); console.log('All clients reset:', resetAll.success); // Delete clients who have exceeded their traffic limit const deleteDepleted = await client.deleteDepletedClients(inboundId); console.log('Depleted clients removed:', deleteDepleted.success); } catch (error) { console.error('Traffic operation failed:', error.message); } // Output: // Traffic reset successfully for user@example.com // All clients reset: true // Depleted clients removed: true ``` ## Credential Generation - Bulk Client Creation Generate multiple credentials at once for different protocols ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); // Generate 10 VLESS credentials const vlessCredentials = client.generateBulkCredentials('vless', 10, { flow: 'xtls-rprx-vision' }); console.log('Generated VLESS credentials:'); vlessCredentials.forEach((cred, index) => { console.log(`${index + 1}. UUID: ${cred.id}, Email: ${cred.email}`); }); // Generate Trojan credentials const trojanCredentials = client.generateBulkCredentials('trojan', 5, { passwordLength: 32 }); console.log('\nGenerated Trojan credentials:'); trojanCredentials.forEach((cred, index) => { console.log(`${index + 1}. Password: ${cred.password}, Email: ${cred.email}`); }); // Generate Shadowsocks credentials with recommended cipher const recommendedCipher = client.getRecommendedShadowsocksCipher(); const ssCredentials = client.generateBulkCredentials('shadowsocks', 3, { method: recommendedCipher }); console.log('\nGenerated Shadowsocks credentials:'); ssCredentials.forEach((cred, index) => { console.log(`${index + 1}. Method: ${cred.method}, Password: ${cred.password}`); }); // Output: // Generated VLESS credentials: // 1. UUID: a1b2c3d4-e5f6-4789-0abc-def123456789, Email: user_1234567890 // 2. UUID: b2c3d4e5-f6a7-4890-1bcd-ef234567890a, Email: user_1234567891 // ... (8 more) // // Generated Trojan credentials: // 1. Password: 9k8j7h6g5f4d3s2a1q0p9o8i7u6y5t4r, Email: user_1234567900 // ... (4 more) // // Generated Shadowsocks credentials: // 1. Method: 2022-blake3-aes-256-gcm, Password: xYz9AbC3DeF7GhI1 // ... (2 more) ``` ## Credential Generation - WireGuard and Reality Keys Generate cryptographic keys for advanced protocols ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); // Generate WireGuard key pair const wgKeys = client.generateWireGuardKeys(); console.log('WireGuard Keys:'); console.log('Private Key:', wgKeys.privateKey); console.log('Public Key:', wgKeys.publicKey); // Generate client config helper const clientConfig = wgKeys.generateClientConfig(['10.0.0.2/32']); console.log('Client Config:', clientConfig); // Generate Reality keys for censorship resistance const realityKeys = client.generateRealityKeys(); console.log('\nReality Keys:'); console.log('Private Key:', realityKeys.privateKey); console.log('Public Key:', realityKeys.publicKey); // Generate Reality config helper const realityConfig = realityKeys.generateRealityConfig( 'www.google.com:443', ['www.google.com', 'google.com'] ); console.log('Reality Config:', realityConfig); // Validate generated credentials const vlessCredentials = client.generateCredentials('vless'); const validation = client.validateCredentials(vlessCredentials, 'vless'); console.log('\nCredential Validation:', validation); // Output: // WireGuard Keys: // Private Key: yGvN4mP3qR7sT1uV5wX9zA2bC6dE0fG4hI8jK2lM6nO= // Public Key: 1A3bC5dE7fG9hI1jK3lM5nO7pQ9rS1tU3vW5xY7zA9bC= // Client Config: { privateKey: '...', publicKey: '...', allowedIPs: ['10.0.0.2/32'] } // // Reality Keys: // Private Key: kQvX8mP3qR7sT1uV5wX9zA2bC6dE0fG4hI8jK2lM6nO= // Public Key: 9A1bC3dE5fG7hI9jK1lM3nO5pQ7rS9tU1vW3xY5zA7bC= // Reality Config: { dest: 'www.google.com:443', serverNames: [...], ... } // // Credential Validation: { valid: true, errors: [] } ``` ## Server Management - Status and Monitoring Monitor server health and online clients ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); try { // Get server status const status = await client.getServerStatus(); if (status.success) { const obj = status.obj; console.log('Server Status:'); console.log(`CPU: ${obj.cpu}%`); console.log(`Memory: ${(obj.mem.current / 1024 / 1024).toFixed(2)} MB / ${(obj.mem.total / 1024 / 1024).toFixed(2)} MB`); console.log(`Uptime: ${Math.floor(obj.uptime / 3600)} hours`); console.log(`Xray Version: ${obj.xray?.version}`); } // Get online clients const onlineClients = await client.getOnlineClients(); if (onlineClients.success) { console.log(`\nOnline Clients: ${onlineClients.obj?.length || 0}`); onlineClients.obj?.forEach(client => { console.log(`- ${client.email} (${client.ip})`); }); } // Get Xray version const xrayVersion = await client.getXrayVersion(); console.log('\nXray Version:', xrayVersion.obj); } catch (error) { console.error('Server monitoring failed:', error.message); } // Output: // Server Status: // CPU: 12.5% // Memory: 512.34 MB / 2048.00 MB // Uptime: 168 hours // Xray Version: 1.8.4 // // Online Clients: 3 // - user1@example.com (192.168.1.100) // - user2@example.com (192.168.1.101) // - user3@example.com (192.168.1.102) // // Xray Version: Xray 1.8.4 (Xray, Penetrates Everything.) Custom (go1.21.3 linux/amd64) ``` ## Server Management - Backup and Restore Create and manage system backups ```javascript const client = new ThreeXUI( process.env.PANEL_URL, process.env.PANEL_USERNAME, process.env.PANEL_PASSWORD ); try { // Create backup const backup = await client.createBackup(); if (backup.success) { console.log('Backup created successfully!'); console.log('Backup file:', backup.obj); } // Send backup to Telegram bot (if configured) const tgBackup = await client.backupToTgBot(); if (tgBackup.success) { console.log('Backup sent to Telegram successfully!'); } // Restart Xray service const restart = await client.restartXrayService(); console.log('Xray service restarted:', restart.success); // Get panel logs (last 50 entries) const logs = await client.getPanelLogs(50); console.log('Recent logs:', logs.obj?.slice(0, 3)); } catch (error) { console.error('Backup operation failed:', error.message); } // Output: // Backup created successfully! // Backup file: /opt/3x-ui/bin/backup/3x-ui_backup_2025_11_30_10_00_00.db // Backup sent to Telegram successfully! // Xray service restarted: true // Recent logs: ['[INFO] Service started', '[INFO] Client connected', ...] ``` ## Web Integration - Express Middleware Integrate with Express.js applications ```javascript const express = require('express'); const { createExpressMiddleware } = require('3xui-api-client'); const app = express(); // Add 3x-ui middleware app.use(createExpressMiddleware({ baseURL: process.env.PANEL_URL, username: process.env.PANEL_USERNAME, password: process.env.PANEL_PASSWORD, sessionKey: 'threeXUIClient' // Accessible via req.threeXUIClient })); // Use in routes app.get('/api/inbounds', async (req, res) => { try { const inbounds = await req.threeXUIClient.getInbounds(); res.json(inbounds); } catch (error) { res.status(500).json({ error: error.message }); } }); app.post('/api/client/create', async (req, res) => { try { const { inboundId, protocol, email } = req.body; const result = await req.threeXUIClient.addClientWithCredentials( inboundId, protocol, { email } ); res.json(result); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () => { console.log('Server running on port 3000'); }); // Client request example: // POST http://localhost:3000/api/client/create // Body: { "inboundId": 1, "protocol": "vless", "email": "newuser@example.com" } // Response: { "success": true, "credentials": { "id": "...", "email": "..." } } ``` ## Web Integration - Next.js API Routes Use with Next.js serverless functions ```javascript // pages/api/vpn/inbounds.js import { createNextjsRoutes } from '3xui-api-client'; const routes = createNextjsRoutes({ baseURL: process.env.PANEL_URL, username: process.env.PANEL_USERNAME, password: process.env.PANEL_PASSWORD }); export default async function handler(req, res) { if (req.method === 'GET') { try { const client = await routes.getClient(); const inbounds = await client.getInbounds(); res.status(200).json(inbounds); } catch (error) { res.status(500).json({ error: error.message }); } } else { res.status(405).json({ error: 'Method not allowed' }); } } // pages/api/vpn/client.js export default async function handler(req, res) { const client = await routes.getClient(); if (req.method === 'POST') { const { inboundId, protocol, email, totalGB, expiryDays } = req.body; try { const result = await client.addClientWithCredentials(inboundId, protocol, { email, totalGB, expiryTime: Date.now() + (expiryDays * 24 * 60 * 60 * 1000) }); res.status(200).json(result); } catch (error) { res.status(500).json({ error: error.message }); } } else if (req.method === 'DELETE') { const { inboundId, clientId } = req.query; try { const result = await client.deleteClient(inboundId, clientId); res.status(200).json(result); } catch (error) { res.status(500).json({ error: error.message }); } } } // Usage from frontend: // const response = await fetch('/api/vpn/client', { // method: 'POST', // headers: { 'Content-Type': 'application/json' }, // body: JSON.stringify({ inboundId: 1, protocol: 'vless', email: 'user@example.com', totalGB: 50, expiryDays: 30 }) // }); ``` ## Summary The 3xui-api-client library serves as a production-ready solution for managing VPN infrastructure built on 3x-ui panels. Its primary use cases include building VPN service provider platforms where automated client provisioning and billing are essential, creating monitoring dashboards that track real-time traffic and server health, implementing self-service portals where users can manage their own VPN accounts, and developing administrative tools for bulk client management and server maintenance. The library eliminates common pain points such as manual credential generation, session management complexity, and protocol-specific configuration challenges. Integration patterns supported by the library range from simple standalone scripts for server administration to complex multi-tier web applications with distributed session storage. The library seamlessly integrates with popular web frameworks (Express.js, Next.js) and supports both RESTful API backends and serverless architectures. Its built-in security features including input validation, rate limiting, secure credential generation, and automatic error sanitization make it suitable for production environments. Whether you're building a commercial VPN service, managing internal proxy infrastructure, or creating automated DevOps tools, the 3xui-api-client provides the foundation for reliable, scalable, and secure 3x-ui panel management.