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

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

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.

npm version npm downloads GitHub stars Node.js Version License: Apache 2.0 Maintenance TypeScript

🚀 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-client

Quick 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 /login endpoint
  • 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 clients
  • getPagedClients(params) - Get paginated client list
  • getClient(email) - Get specific client by email
  • getClientTraffic(email) - Get client traffic statistics
  • getSubLinks(subId) - Get subscription links by subscription ID
  • getClientLinks(email) - Get generic client links
  • getGroups() - Get all client groups
  • getGroupEmails(groupName) - Get emails in specific group
  • getOnlines() - Get currently online clients
  • getModernLastOnline() - Get last online status
  • getModernClientIps(email) - Get client IP list

Write Operations

  • addModernClient(data) - Add new client (modern API)
  • updateModernClient(email, data) - Update client details
  • deleteModernClient(email) - Delete client
  • attachClientToInbounds(email, data) - Attach client to inbounds
  • detachClientFromInbounds(email, data) - Detach client from inbounds
  • resetModernClientTrafficByEmail(email) - Reset client traffic
  • updateModernClientTrafficByEmail(email, data) - Update traffic limits
  • clearModernClientIps(email) - Clear client IP restrictions

Bulk Operations

  • bulkCreateModernClients(data) - Bulk create clients
  • bulkDeleteModernClients(data) - Bulk delete clients
  • bulkAttachModernClients(data) - Bulk attach to inbounds
  • bulkDetachModernClients(data) - Bulk detach from inbounds
  • bulkAdjustModernClients(data) - Bulk adjust settings
  • bulkResetTrafficModernClients(data) - Bulk reset traffic
  • resetAllModernClientTraffics() - Reset all client traffic
  • deleteDepletedModernClients() - Delete depleted clients

Group Management

  • createGroup(data) - Create client group
  • renameGroup(data) - Rename existing group
  • deleteGroup(data) - Delete group
  • bulkAddGroups(data) - Bulk add groups
  • bulkRemoveGroups(data) - Bulk remove groups

Client Management (Legacy API)

  • addClient(clientConfig) - Add client
  • updateClient(clientId, clientConfig) - Update client
  • deleteClient(inboundId, clientId) - Delete client
  • deleteClientByEmail(inboundId, email) - Delete by email
  • getClientTrafficsByEmail(email) - Get traffic by email
  • getClientTrafficsById(id) - Get traffic by ID
  • getClientIps(email) - Get client IPs
  • clearClientIps(email) - Clear IP restrictions
  • updateClientTraffic(email, trafficConfig) - Update traffic limits
  • resetClientTraffic(inboundId, email) - Reset traffic
  • resetAllTraffics() - Reset all traffic globally
  • resetAllClientTraffics(inboundId) - Reset inbound traffic
  • deleteDepletedClients(inboundId) - Delete depleted clients

Inbound Management

  • getInbounds() - Get all inbounds
  • getInbound(id) - Get specific inbound
  • addInbound(inboundConfig) - Add new inbound
  • updateInbound(id, inboundConfig) - Update inbound
  • deleteInbound(id) - Delete inbound
  • importInbounds(inbounds) - Bulk import inbounds
  • getLastOnline() - Get last online info

Node Management

  • getNodes() - Get all nodes
  • getNode(id) - Get specific node
  • getNodeHistory(id, metric, bucket) - Get node metrics history
  • addNode(data) - Add new node
  • updateNode(id, data) - Update node
  • deleteNode(id) - Delete node
  • setNodeEnable(id) - Enable node
  • testNode(data) - Test node connectivity
  • probeNode(id) - Probe node status

Custom Geo Management

  • getCustomGeos() - Get custom geo sites/IPs
  • getGeoAliases() - Get geo aliases
  • addCustomGeo(data) - Add custom geo
  • updateCustomGeo(id, data) - Update geo
  • deleteCustomGeo(id) - Delete geo
  • downloadCustomGeo(id) - Download geo data
  • updateAllCustomGeo() - Update all geo data

Server Management

  • getServerStatus() - Get CPU, RAM, uptime
  • getCPUHistory(bucket) - Get CPU usage history
  • getXrayVersion() - Get Xray version
  • getConfigJson() - Get Xray config JSON
  • getDb() - Download database
  • stopXrayService() - Stop Xray core
  • restartXrayService() - Restart Xray core
  • installXray(version) - Install specific Xray version
  • getPanelLogs(count) - Get panel logs
  • getXrayLogs(count) - Get Xray logs
  • updateGeofile(fileName) - Update GeoIP/GeoSite files
  • importDB(formData) - Import database

Panel Settings

  • getAllSettings() - Get all panel settings
  • updateSetting(settings) - Update settings
  • updateUser(oldUsername, oldPassword, newUsername, newPassword) - Change admin credentials
  • restartPanel() - Restart panel
  • getDefaultSettings() - Get default settings
  • getDefaultJsonConfig() - Get default Xray JSON config

Xray Configuration

  • getXrayConfig() - Get Xray configuration
  • updateXrayConfig(config) - Update Xray configuration
  • manageWarp(action, data) - Manage WARP settings
  • getOutboundsTraffic() - Get outbound traffic statistics
  • resetOutboundsTraffic() - Reset outbound traffic
  • getXrayResult() - Get Xray execution result

Server-Side Generators

  • getNewUUID() - Generate UUID server-side
  • getNewX25519Cert() - Generate X25519 certificate
  • getNewmldsa65() - Generate MLDSA65 key
  • getNewmlkem768() - Generate ML-KEM-768 key
  • getNewVlessEnc() - Generate VLESS encryption
  • getNewEchCert() - Generate ECH certificate

Credential Generation

  • generateCredentials(protocol, options) - Generate protocol-specific credentials
  • generateUUID(secure) - Generate UUID
  • generatePassword(length, options) - Generate password
  • generateBulkCredentials(protocol, count, options) - Bulk generate credentials
  • generateWireGuardKeys() - Generate WireGuard key pair
  • generateRealityKeys() - Generate Reality key pair
  • generatePort(min, max) - Generate random port
  • getShadowsocksCiphers() - List SS cipher methods
  • getRecommendedShadowsocksCipher() - Get recommended cipher
  • validateCredentials(credentials, protocol) - Validate credentials

Enhanced Client Management

  • addClientWithCredentials(inboundId, protocol, options) - Add client with auto-generated credentials
  • updateClientWithCredentials(clientId, inboundId, options) - Update client with credential management

Session Management

  • login(forceRefresh) - Authenticate with credentials/token
  • logout() - Clear session
  • isSessionValid() - Check session validity
  • getSessionStats() - Get session statistics
  • clearAllSessions() - Clear all cached sessions
  • getTwoFactorEnable() - Check 2FA status

System

  • getOnlineClients() - Get online clients
  • createBackup() - Create system backup
  • backupToTgBot() - Send backup to Telegram
  • getSecurityStats() - Get security monitoring data

Documentation

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

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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add 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

FAQ

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:

  1. Use a shared external store (RedisSessionStore or DatabaseSessionStore) so instances can reuse existing sessions instead of re-authenticating every time.
  2. Re-login backoff — the client applies a configurable delay (default 500 ms) before each forced re-login on a 401 response. 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)
});
  1. Rate limit awarenessmaxLoginRetries is 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.