npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

3xui-api-client

v2.1.1

Published

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

Downloads

436

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 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.