Skip to content

iamhelitha/3xui-api-client

Repository files navigation

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 and cookie handling
  • βœ… Security - Built-in input validation, secure headers, and rate limiting
  • βœ… 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);
  });

Configuration & Best Practices

Using Environment Variables (Recommended)

Never hardcode your credentials in your code. Use environment variables to store sensitive information.

IMPORTANT NOTE: The PANEL_URL should be the root URL of your server WITHOUT the /panel suffix.

  • βœ… Correct: https://your-domain.com:2053 or https://your-domain.com/secret-path
  • ❌ Incorrect: https://your-domain.com:2053/panel

The library automatically appends /panel and other necessary paths. Including it in your configuration will cause 404 errors.

  1. Create a .env file in your project root:
PANEL_URL=http://your-server-ip:2053
PANEL_USERNAME=admin
PANEL_PASSWORD=your_secure_password
  1. Install dotenv:
npm install dotenv
  1. Initialize the client:
require('dotenv').config();
const ThreeXUI = require('3xui-api-client');

const client = new ThreeXUI(
    process.env.PANEL_URL,
    process.env.PANEL_USERNAME,
    process.env.PANEL_PASSWORD
);

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

Server-Side Cookie Storage (Recommended)

For production applications, store the session cookie securely on your server. The login() method returns the cookie for this purpose:

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();
      
      // The cookie is returned in the login result
      this.sessionCookie = loginResult.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();
  }
}

Security Features

The library includes several security enhancements:

  • Input Validation: Validates URLs, usernames, and passwords to prevent injection attacks.
  • Secure Headers: Automatically adds security headers to requests.
  • Rate Limiting: Prevents abuse by limiting request rates (configurable).
  • Error Sanitization: Hides sensitive details in production errors.

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);

Send Backup to Telegram Bot

const tgResult = await client.backupToTgBot();
console.log('Backup sent to Telegram:', tgResult);

Get Server Status

const status = await client.getServerStatus();
console.log('Server status:', status);

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.

About

A Node.js client library for 3x-ui panel API management with automatic session handling and complete API coverage

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published