3xui-api-client
v3.1.2
Published
Node.js API client for the 3x-ui panel (VLESS, VMess, Trojan, Shadowsocks, WireGuard, Reality) with automatic session management, credential generation, and full REST API coverage
Maintainers
Keywords
Readme
3xui-api-client
A Node.js / TypeScript API client for the 3x-ui panel (Xray-core), with easy-to-use methods for managing inbounds and clients across VLESS, VMess, Trojan, Shadowsocks, WireGuard, and Reality protocols.
🚀 Context7 MCP Integration
This library is available through Context7 MCP for enhanced development experience with intelligent documentation integration. Use the package name 3xui-api-client to get AI-powered context and documentation.
Table of Contents
Features
- ✅ Dual Panel Support - Works with both modern (React, v2.x+) and legacy (Vue, v1.x) 3x-ui panels
- ✅ Auto-Detection - Automatically detects panel version and uses correct endpoints
- ✅ API Token Authentication - Support for API token auth (3x-ui v3.0.2+) and cookie-based login
- ✅ Automatic Credential Generation - Built-in UUID, password, and key pair generators
- ✅ Session Management - Automatic login, session caching, and expiry handling
- ✅ Security - Input validation, secure headers, rate limiting, and error sanitization
- ✅ Modern API Support - Complete modern API (v2.x+) with advanced client management
- ✅ Legacy API Support - Full backward compatibility with legacy API methods
- ✅ TypeScript Definitions - Complete type definitions for IDE support
- ✅ 124 API Methods - Comprehensive coverage of all 3x-ui panel operations
Installation
npm install 3xui-api-clientQuick Start
Cookie-Based Authentication
const ThreeXUI = require('3xui-api-client');
const client = new ThreeXUI('https://your-3xui-server.com', 'username', 'password');
// Get all inbounds
const inbounds = await client.getInbounds();
console.log(inbounds);API Token Authentication (v3.0.2+)
const client = new ThreeXUI('https://your-3xui-server.com', {
token: 'your-api-token'
});
const inbounds = await client.getInbounds();Panel Version Support
This library automatically supports both modern and legacy 3x-ui panels:
// Automatic detection (recommended)
// Works with both modern and legacy panels
const client = new ThreeXUI('https://your-3xui-server.com', 'username', 'password');
await client.login();
// Automatically detects panel version and uses correct endpoints
// Explicit version (optional, for performance)
const client = new ThreeXUI('https://your-3xui-server.com', 'username', 'password', {
panelVersion: 'modern' // or 'legacy' or 'auto' (default)
});Supported Panel Types:
- ✅ Modern Panels - React-based, v2.x+ with
/panel/api/*endpoints - ✅ Legacy Panels - Vue-based, v1.x with
/loginendpoint - ✅ Auto-Detection - Tries modern first, falls back to legacy if needed
- ✅ Session Caching - Detected version is cached for faster subsequent logins
See PANEL-VERSION-SUPPORT.md for detailed version support documentation.
API Methods
Client Management (Modern API - v2.x+)
Read Operations
getClients()- Get all clientsgetPagedClients(params)- Get paginated client listgetClient(email)- Get specific client by emailgetClientTraffic(email)- Get client traffic statisticsgetSubLinks(subId)- Get subscription links by subscription IDgetClientLinks(email)- Get generic client linksgetGroups()- Get all client groupsgetGroupEmails(groupName)- Get emails in specific groupgetOnlines()- Get currently online clientsgetModernLastOnline()- Get last online statusgetModernClientIps(email)- Get client IP list
Write Operations
addModernClient(data)- Add new client (modern API)updateModernClient(email, data)- Update client detailsdeleteModernClient(email)- Delete clientattachClientToInbounds(email, data)- Attach client to inboundsdetachClientFromInbounds(email, data)- Detach client from inboundsresetModernClientTrafficByEmail(email)- Reset client trafficupdateModernClientTrafficByEmail(email, data)- Update traffic limitsclearModernClientIps(email)- Clear client IP restrictions
Bulk Operations
bulkCreateModernClients(data)- Bulk create clientsbulkDeleteModernClients(data)- Bulk delete clientsbulkAttachModernClients(data)- Bulk attach to inboundsbulkDetachModernClients(data)- Bulk detach from inboundsbulkAdjustModernClients(data)- Bulk adjust settingsbulkResetTrafficModernClients(data)- Bulk reset trafficresetAllModernClientTraffics()- Reset all client trafficdeleteDepletedModernClients()- Delete depleted clients
Group Management
createGroup(data)- Create client grouprenameGroup(data)- Rename existing groupdeleteGroup(data)- Delete groupbulkAddGroups(data)- Bulk add groupsbulkRemoveGroups(data)- Bulk remove groups
Client Management (Legacy API)
addClient(clientConfig)- Add clientupdateClient(clientId, clientConfig)- Update clientdeleteClient(inboundId, clientId)- Delete clientdeleteClientByEmail(inboundId, email)- Delete by emailgetClientTrafficsByEmail(email)- Get traffic by emailgetClientTrafficsById(id)- Get traffic by IDgetClientIps(email)- Get client IPsclearClientIps(email)- Clear IP restrictionsupdateClientTraffic(email, trafficConfig)- Update traffic limitsresetClientTraffic(inboundId, email)- Reset trafficresetAllTraffics()- Reset all traffic globallyresetAllClientTraffics(inboundId)- Reset inbound trafficdeleteDepletedClients(inboundId)- Delete depleted clients
Inbound Management
getInbounds()- Get all inboundsgetInbound(id)- Get specific inboundaddInbound(inboundConfig)- Add new inboundupdateInbound(id, inboundConfig)- Update inbounddeleteInbound(id)- Delete inboundimportInbounds(inbounds)- Bulk import inboundsgetLastOnline()- Get last online info
Node Management
getNodes()- Get all nodesgetNode(id)- Get specific nodegetNodeHistory(id, metric, bucket)- Get node metrics historyaddNode(data)- Add new nodeupdateNode(id, data)- Update nodedeleteNode(id)- Delete nodesetNodeEnable(id)- Enable nodetestNode(data)- Test node connectivityprobeNode(id)- Probe node status
Custom Geo Management
getCustomGeos()- Get custom geo sites/IPsgetGeoAliases()- Get geo aliasesaddCustomGeo(data)- Add custom geoupdateCustomGeo(id, data)- Update geodeleteCustomGeo(id)- Delete geodownloadCustomGeo(id)- Download geo dataupdateAllCustomGeo()- Update all geo data
Server Management
getServerStatus()- Get CPU, RAM, uptimegetCPUHistory(bucket)- Get CPU usage historygetXrayVersion()- Get Xray versiongetConfigJson()- Get Xray config JSONgetDb()- Download databasestopXrayService()- Stop Xray corerestartXrayService()- Restart Xray coreinstallXray(version)- Install specific Xray versiongetPanelLogs(count)- Get panel logsgetXrayLogs(count)- Get Xray logsupdateGeofile(fileName)- Update GeoIP/GeoSite filesimportDB(formData)- Import database
Panel Settings
getAllSettings()- Get all panel settingsupdateSetting(settings)- Update settingsupdateUser(oldUsername, oldPassword, newUsername, newPassword)- Change admin credentialsrestartPanel()- Restart panelgetDefaultSettings()- Get default settingsgetDefaultJsonConfig()- Get default Xray JSON config
Xray Configuration
getXrayConfig()- Get Xray configurationupdateXrayConfig(config)- Update Xray configurationmanageWarp(action, data)- Manage WARP settingsgetOutboundsTraffic()- Get outbound traffic statisticsresetOutboundsTraffic()- Reset outbound trafficgetXrayResult()- Get Xray execution result
Server-Side Generators
getNewUUID()- Generate UUID server-sidegetNewX25519Cert()- Generate X25519 certificategetNewmldsa65()- Generate MLDSA65 keygetNewmlkem768()- Generate ML-KEM-768 keygetNewVlessEnc()- Generate VLESS encryptiongetNewEchCert()- Generate ECH certificate
Credential Generation
generateCredentials(protocol, options)- Generate protocol-specific credentialsgenerateUUID(secure)- Generate UUIDgeneratePassword(length, options)- Generate passwordgenerateBulkCredentials(protocol, count, options)- Bulk generate credentialsgenerateWireGuardKeys()- Generate WireGuard key pairgenerateRealityKeys()- Generate Reality key pairgeneratePort(min, max)- Generate random portgetShadowsocksCiphers()- List SS cipher methodsgetRecommendedShadowsocksCipher()- Get recommended ciphervalidateCredentials(credentials, protocol)- Validate credentials
Enhanced Client Management
addClientWithCredentials(inboundId, protocol, options)- Add client with auto-generated credentialsupdateClientWithCredentials(clientId, inboundId, options)- Update client with credential management
Session Management
login(forceRefresh)- Authenticate with credentials/tokenlogout()- Clear sessionisSessionValid()- Check session validitygetSessionStats()- Get session statisticsclearAllSessions()- Clear all cached sessionsgetTwoFactorEnable()- Check 2FA status
System
getOnlineClients()- Get online clientscreateBackup()- Create system backupbackupToTgBot()- Send backup to TelegramgetSecurityStats()- Get security monitoring data
Documentation
For comprehensive guides, examples, and implementation patterns, visit our Wiki:
- 📚 Use Cases & Examples
- 🔐 Authentication Guide
- 🌐 Inbound Management
- 👥 Client Management
- 📊 Traffic Management
- ⚙️ System Operations
- 🌐 Modern API Guide
Requirements
- Node.js >= 14.0.0
- 3x-ui panel v2.0+ (or v3.0.2+ for API token authentication)
- API access enabled on your 3x-ui server
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Testing
# Run login test
npm run test:login
# Run all tests
npm testFAQ
Q: Do I need to call login() explicitly?
A: No, the client automatically logs in before the first API call. Just create the client and start using it.
Q: Can I use API tokens instead of username/password?
A: Yes, use { token: 'your-api-token' } instead of username/password (requires 3x-ui v3.0.2+).
Q: How do I store session cookies securely? A: See the Session Security section below and the Authentication Guide for server-side storage patterns.
Q: Which authentication method is more secure? A: API tokens are recommended for production. See Authentication Guide for comparison.
Q: Can I use the client in browsers? A: No, this is a Node.js library. Use it on your server side with proper CORS/security headers.
Q: How do I migrate from v2.x to v3.x? A: The library is backward compatible. See CHANGELOG.md for breaking changes (if any).
Q: Can I bulk operations with this client?
A: Yes, use the bulk* methods for efficient batch operations. See Client Management for examples.
Session Security
[!IMPORTANT] The 3x-ui session cookie grants full admin access to your panel. Treat it with the same care as a password or API secret.
Cookie storage is unencrypted by default
Both built-in session stores save the cookie in plaintext:
| Store | Where the cookie lives |
|---|---|
| MemorySessionStore (default) | Plain JS Map in process heap |
| DatabaseSessionStore | session_data TEXT column, no encryption |
| RedisSessionStore | Plain string value in Redis |
Recommendations:
- Memory store — safe for single-process, single-instance deployments. In shared/multi-tenant environments a heap dump exposes live admin cookies. Prefer Redis or DB stores with proper access controls.
- Database store — restrict the DB user to only the sessions table with the minimum required privileges, and enable encryption-at-rest on the database itself.
- Redis store — use Redis ACLs to restrict key-space access and enable TLS for the Redis connection.
- For the highest security, use API tokens (
{ token: 'your-api-token' }) instead of username/password — tokens can be scoped and revoked without a session cookie.
Session key is deterministic
The cache key is sha256(baseURL:username). It is an intentionally stable lookup key, not a secret. Anyone with read access to the session store can correlate rows to specific panels and users. Protect the values (cookies), not the keys.
Serverless and multi-instance deployments
Each serverless cold start (e.g. Vercel, AWS Lambda) creates a fresh in-memory session, triggering a /login call per instance. A few things to keep in mind:
- Use a shared external store (
RedisSessionStoreorDatabaseSessionStore) so instances can reuse existing sessions instead of re-authenticating every time. - Re-login backoff — the client applies a configurable delay (default 500 ms) before each forced re-login on a
401response. This prevents a burst of cold starts from simultaneously hammering the panel login endpoint and tripping rate-limiting or fail2ban rules. You can tune it:
const client = new XuiApiClient({
baseURL: 'https://your-panel.example.com',
username: 'admin',
password: 'secret',
maxLoginRetries: 3, // max 401-triggered re-login attempts (default: 3)
loginRetryBackoff: 1000, // ms to wait before each retry (default: 500, set 0 to disable)
});- Rate limit awareness —
maxLoginRetriesis per-instance. Across many concurrent instances you can still exceed the panel's login-attempt limit. If your panel has fail2ban enabled, ensure your egress IP is whitelisted or use API token auth to avoid the login flow entirely.
License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Support
Author
Helitha Guruge - @iamhelitha
⚠️ Security Notice: Always store credentials and session cookies securely. Never expose them in client-side code or commit them to version control.
