Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

3xui-api-client

iamhelitha150MIT2.1.0TypeScript support: included

A Node.js client library for 3x-ui panel API with built-in credential generation, session management, and web integration support

3x-ui, 3xui, api, client, vpn, proxy, panel, xray, v2ray, server-management, api-client, network-management, credential-generation, session-management, web-integration, express-middleware, nextjs, vless, vmess, trojan, shadowsocks, wireguard, reality

readme

3xui-api-client

A Node.js client library for 3x-ui panel API that provides easy-to-use methods for managing your 3x-ui server.

npm version License: MIT

Features

  • Authentication - Secure login with automatic session management
  • Inbound Management - Get, add, update, and delete inbounds
  • Client Management - Add, update, delete clients and monitor traffic
  • Traffic Management - Monitor, reset, and manage traffic limits
  • System Operations - Backup creation and online client monitoring
  • Complete API Coverage - All 19 API routes fully tested and working

Installation

npm install 3xui-api-client

Context7 MCP Integration

This library can be implemented with the help of Context7 MCP. Use the package name 3xui-api-client to get context and documentation through Context7's Model Context Protocol integration.

Learn more about Context7 MCP for enhanced development experience.

Quick Start

const ThreeXUI = require('3xui-api-client');

const client = new ThreeXUI('https://your-3xui-server.com', 'username', 'password');

// Get all inbounds
client.getInbounds()
  .then(inbounds => {
    console.log('Inbounds:', inbounds);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });

Authentication & Security

Automatic Login

The client automatically handles authentication. When you make your first API call, it will:

  1. Login with your credentials
  2. Store the session cookie
  3. Use the cookie for subsequent requests
  4. Automatically re-login if the session expires

For production applications, store the session cookie securely on your server:

const ThreeXUI = require('3xui-api-client');

class SecureThreeXUIManager {
  constructor(baseURL, username, password) {
    this.client = new ThreeXUI(baseURL, username, password);
    this.sessionCookie = null;
  }

  async ensureAuthenticated() {
    if (!this.sessionCookie) {
      const loginResult = await this.client.login();
      this.sessionCookie = this.client.cookie;

      // Store in secure session storage (Redis, database, etc.)
      await this.storeSessionSecurely(this.sessionCookie);
    } else {
      // Restore from secure storage
      this.client.cookie = this.sessionCookie;
      this.client.api.defaults.headers.Cookie = this.sessionCookie;
    }
  }

  async storeSessionSecurely(cookie) {
    // Example: Store in Redis with expiration
    // await redis.setex('3xui_session', 3600, cookie);

    // Example: Store in database
    // await db.sessions.upsert({ service: '3xui', cookie, expires_at: new Date(Date.now() + 3600000) });
  }

  async getInbounds() {
    await this.ensureAuthenticated();
    return this.client.getInbounds();
  }
}

API Reference

Constructor

new ThreeXUI(baseURL, username, password)
  • baseURL (string): Your 3x-ui server URL (e.g., 'https://your-server.com')
  • username (string): Admin username
  • password (string): Admin password

Inbound Management (✅ Tested & Working)

Get All Inbounds

const inbounds = await client.getInbounds();
console.log(inbounds);

Get Specific Inbound

const inbound = await client.getInbound(inboundId);
console.log(inbound);

Add New Inbound

const inboundConfig = {
  remark: "My VPN Server",
  port: 443,
  protocol: "vless",
  settings: {
    // Your inbound settings
  }
};

const result = await client.addInbound(inboundConfig);
console.log('Inbound added:', result);

Update Inbound

const updatedConfig = {
  remark: "Updated VPN Server",
  // Other updated settings
};

const result = await client.updateInbound(inboundId, updatedConfig);
console.log('Inbound updated:', result);

Delete Inbound

const result = await client.deleteInbound(inboundId);
console.log('Inbound deleted:', result);

Client Management (✅ Tested & Working)

Add Client to Inbound

const clientConfig = {
  id: inboundId,
  settings: JSON.stringify({
    clients: [{
      id: "client-uuid-here",
      email: "user23c5n7",
      limitIp: 0,
      totalGB: 0,
      expiryTime: 0,
      enable: true
    }]
  })
};

const result = await client.addClient(clientConfig);

Update Client

const updateConfig = {
  id: inboundId,
  settings: JSON.stringify({
    clients: [/* updated client settings */]
  })
};

const result = await client.updateClient(clientUUID, updateConfig);

Delete Client

const result = await client.deleteClient(inboundId, clientUUID);

Get Client Traffic by Email

const traffic = await client.getClientTrafficsByEmail("user23c5n7");
console.log('Client traffic:', traffic);

Get Client Traffic by UUID

const traffic = await client.getClientTrafficsById("client-uuid");
console.log('Client traffic:', traffic);

Manage Client IPs

// Get client IPs
const ips = await client.getClientIps("user23c5n7");

// Clear client IPs
const result = await client.clearClientIps("user23c5n7");

Traffic Management (✅ Tested & Working)

Reset Individual Client Traffic

const result = await client.resetClientTraffic(inboundId, "user23c5n7");

Reset All Traffic (Global)

const result = await client.resetAllTraffics();

Reset All Client Traffic in Inbound

const result = await client.resetAllClientTraffics(inboundId);

Delete Depleted Clients

const result = await client.deleteDepletedClients(inboundId);

System Operations (✅ Tested & Working)

Get Online Clients

const onlineClients = await client.getOnlineClients();
console.log('Currently online:', onlineClients);

Create System Backup

const result = await client.createBackup();
console.log('Backup created:', result);

Documentation

For comprehensive guides, examples, and implementation patterns, visit our Wiki:

Error Handling

try {
  const inbounds = await client.getInbounds();
  console.log(inbounds);
} catch (error) {
  if (error.message.includes('Login failed')) {
    console.error('Authentication error:', error.message);
  } else if (error.response?.status === 401) {
    console.error('Unauthorized - check your credentials');
  } else {
    console.error('API error:', error.message);
  }
}

Requirements

  • Node.js >= 14.0.0
  • 3x-ui panel with API access enabled

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Testing

# Run login test
npm run test:login

# Run all tests
npm test

License

This project is licensed under the MIT License - 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.

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[2.1.0] - 2025-08-30

Added

  • 🔥 Firestore Session Store Support - Custom session handler for Firebase Firestore integration
  • 📝 Enhanced Wiki Documentation - Comprehensive guides with real-world examples and integration patterns
  • 🔍 Client Identifier Clarification - Clear documentation that 'email' field is an identifier, not a real email address

Enhanced

  • 📚 Authentication Guide - Added detailed session/cookie flow documentation and Firestore integration example
  • 👥 Client Management Guide - Clarified email field semantics and added identifier generation examples
  • 🛠️ Inbound Management Guide - Added protocol-specific authentication method explanations
  • 🏠 Home Documentation - Improved navigation and cross-references between guides

Documentation

  • Session Management: Added comprehensive Firestore adapter example with cleanup patterns
  • API Flow Clarification: Documented that all API calls automatically include stored session cookies
  • Client Identifiers: Clarified that 'email' fields use random strings (e.g., '5yhuih4hg93') for privacy
  • Integration Examples: Enhanced web integration patterns for Express.js and Next.js
  • Security Best Practices: Consolidated security guidance in Authentication Guide

Removed

  • Removed any references to email generation functionality for clarity
  • Cleaned up duplicate content across wiki files

Fixed

  • Corrected misconceptions about email field usage in 3x-ui
  • Improved consistency across documentation

[2.0.0] - 2025-06-25

Added

  • 🎯 Built-in Credential Generation System - Automatic generation of random passwords, UUIDs, and client identifiers
  • 🔧 Advanced Session Management - Intelligent session caching, automatic renewal, and multi-server support
  • 🌐 Web Integration Support - Express.js and Next.js middleware for seamless web app integration
  • 🛡️ Enhanced Security Framework - Input validation, security monitoring, and secure headers management
  • 📦 Modular Architecture - New src/ directory structure with specialized modules:
    • CredentialGenerator.js - Random credential generation utilities
    • SessionManager.js - Advanced session handling and caching
    • WebMiddleware.js - Express/Next.js integration helpers
    • ProtocolBuilders.js - Automated inbound configuration builders
    • SecurityEnhancer.js - Security validation and monitoring

Enhanced

  • 🔐 Improved Authentication - More robust session handling with automatic recovery
  • 📊 Better Error Handling - Enhanced error messages and recovery mechanisms
  • 🎨 Developer Experience - Improved TypeScript definitions and code documentation
  • 🧪 Testing Framework - Updated test suite with better coverage and reliability
  • 📝 Documentation - Comprehensive wiki updates with practical examples

New Features

  • Credential Generation:

    • Random password generation with customizable complexity
    • UUID v4 generation for unique client identifiers
    • Secure random string generation for API keys
    • Email-like identifier generation for client management
  • Session Management:

    • Intelligent session caching with TTL support
    • Multi-server session handling
    • Automatic session renewal and cleanup
    • Database-ready session storage format
  • Web Integration:

    • Express.js middleware for route protection
    • Next.js API route helpers
    • Automatic cookie management
    • Request/response transformation utilities
  • Protocol Builders:

    • Automated VLESS configuration generation
    • VMess protocol setup helpers
    • Trojan and Shadowsocks builders
    • Reality and WireGuard configuration support

Changed

  • Breaking Change: Enhanced API structure with new module organization
  • Package Structure: Moved from monolithic to modular architecture
  • Dependencies: Updated to latest stable versions
  • Configuration: Improved configuration options and defaults

Security

  • Enhanced input validation and sanitization
  • Improved session security with automatic cleanup
  • Better error handling to prevent information leakage
  • Security monitoring and alerting capabilities

Developer Experience

  • Better TypeScript support with comprehensive type definitions
  • Improved documentation with real-world examples
  • Enhanced testing framework with automated validation
  • ESLint configuration for code quality

Performance

  • Optimized session management with intelligent caching
  • Reduced API call overhead through better request batching
  • Improved memory usage with automatic cleanup
  • Faster authentication flow with session reuse

[1.0.0] - 2025-06-20

Added

  • Complete API client library for 3x-ui panel management
  • Authentication with automatic session management
  • Inbound management (5 methods): getInbounds, getInbound, addInbound, updateInbound, deleteInbound
  • Client management (7 methods): addClient, updateClient, deleteClient, getClientTrafficsByEmail, getClientTrafficsById, getClientIps, clearClientIps
  • Traffic management (4 methods): resetClientTraffic, resetAllTraffics, resetAllClientTraffics, deleteDepletedClients
  • System operations (2 methods): getOnlineClients, createBackup
  • Comprehensive error handling and automatic re-authentication
  • TypeScript definitions for better developer experience
  • ESM module support alongside CommonJS
  • Complete documentation and wiki guides
  • Interactive testing suite with 19 test files
  • Security best practices implementation

Features

  • 🔐 Secure session-based authentication
  • 🔄 Automatic login retry on session expiry
  • 📊 Complete API coverage (19 routes tested and working)
  • 🛡️ Server-side only design for security
  • 📚 Comprehensive documentation with real-world examples
  • 🧪 Extensive testing suite with actual API responses
  • 📝 TypeScript support for better DX
  • 🔗 Both CommonJS and ESM module support

Security

  • No vulnerabilities in dependencies
  • Secure session cookie handling
  • Server-side only architecture
  • Input validation and error handling
  • Automatic timeout and retry mechanisms

[Unreleased]

Planned

  • GitHub Actions CI/CD pipeline
  • Automated semantic releases
  • Enhanced unit test coverage
  • Performance benchmarking tools
  • Advanced monitoring and analytics