Note
This was created with Kiro and might have some bugs
A comprehensive TypeScript client for the UniFi Controller API, providing type-safe access to all UniFi network management functionality. This library is a complete TypeScript port of the popular PHP UniFi-API-client, offering the same extensive feature set with modern TypeScript benefits.
- π Full Authentication Support - Automatic session management and re-authentication
- π‘ Complete API Coverage - All UniFi Controller API endpoints supported
- π‘οΈ Type Safety - Full TypeScript definitions for all API responses
- π Automatic Retries - Built-in retry logic for network resilience
- πͺ Session Management - Automatic cookie handling and session persistence
- β‘ Modern Async/Await - Promise-based API with async/await support
- π« Request Cancellation - AbortController support for request cancellation
- π Debug Support - Comprehensive logging for troubleshooting
- π Extensive Documentation - Complete JSDoc documentation and examples
npm install unifi-api-tsyarn add unifi-api-tspnpm add unifi-api-tsimport { UniFiClient } from 'unifi-api-ts';
// Create client instance
const client = new UniFiClient({
baseUrl: 'https://unifi.example.com:8443',
username: 'admin',
password: 'your-password',
site: 'default', // optional, defaults to 'default'
verifySsl: false // optional, useful for self-signed certificates
});
// Login and start using the API
async function main() {
try {
// Authenticate
await client.login();
// Get all devices
const devices = await client.list_devices();
console.log(`Found ${devices.length} devices`);
// Get all connected clients
const clients = await client.list_users();
console.log(`Found ${clients.length} connected clients`);
// Logout when done
await client.logout();
} catch (error) {
console.error('Error:', error.message);
}
}
main();The UniFiClientConfig interface supports the following options:
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
baseUrl |
string | β | - | Base URL of your UniFi Controller |
username |
string | β | - | Username for authentication |
password |
string | β | - | Password for authentication |
site |
string | β | 'default' |
Site name to operate on |
timeout |
number | β | 30000 |
Request timeout in milliseconds |
verifySsl |
boolean | β | true |
Whether to verify SSL certificates |
debug |
boolean | β | false |
Enable debug logging |
const client = new UniFiClient({
baseUrl: 'https://192.168.1.1:8443',
username: 'admin',
password: 'mypassword',
site: 'corporate',
timeout: 15000,
verifySsl: false,
debug: true
});// Login (required before making API calls)
await client.login();
// Check authentication status
if (client.isAuthenticated()) {
console.log('Client is authenticated');
}
// Get session information
const sessionInfo = client.getSessionInfo();
console.log(`Logged in as: ${sessionInfo.username}`);
// Logout
await client.logout();// List all UniFi devices (APs, switches, gateways)
const devices = await client.list_devices();
// Get specific device by MAC address
const device = await client.list_devices('aa:bb:cc:dd:ee:ff');
// Get basic device information (faster)
const basicDevices = await client.list_devices_basic();// List all connected clients
const clients = await client.list_users();
// Get specific client by MAC address
const client = await client.list_users('aa:bb:cc:dd:ee:ff');
// Force client reconnection
await client.reconnect_sta('aa:bb:cc:dd:ee:ff');
// Block a client
await client.block_sta('aa:bb:cc:dd:ee:ff');
// Unblock a client
await client.unblock_sta('aa:bb:cc:dd:ee:ff');
// Forget a client (remove from controller memory)
await client.forget_sta('aa:bb:cc:dd:ee:ff');// Authorize guest for 60 minutes
await client.authorize_guest('aa:bb:cc:dd:ee:ff', 60);
// Authorize guest with bandwidth limits (5 Mbps up, 10 Mbps down)
await client.authorize_guest('aa:bb:cc:dd:ee:ff', 60, 5000, 10000);
// Authorize guest with data limit (1 GB)
await client.authorize_guest('aa:bb:cc:dd:ee:ff', 60, undefined, undefined, 1024);
// Revoke guest authorization
await client.unauthorize_guest('aa:bb:cc:dd:ee:ff');The client provides specific error types for different failure scenarios:
import {
AuthenticationError,
NetworkError,
APIError,
TimeoutError,
ConfigurationError
} from 'unifi-api-ts';
try {
await client.login();
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid credentials');
} else if (error instanceof NetworkError) {
console.error('Network connectivity issue');
} else if (error instanceof TimeoutError) {
console.error('Request timed out');
} else if (error instanceof APIError) {
console.error(`API error: ${error.statusCode} - ${error.message}`);
} else if (error instanceof ConfigurationError) {
console.error('Configuration error:', error.message);
}
}All API methods support request cancellation using AbortController:
const controller = new AbortController();
// Cancel the request after 5 seconds
setTimeout(() => controller.abort(), 5000);
try {
const devices = await client.list_devices(undefined, {
signal: controller.signal
});
} catch (error) {
if (error.message.includes('cancelled')) {
console.log('Request was cancelled');
}
}// Get the underlying HTTP client for custom requests
const httpClient = client.getHttpClient();
// Make a custom API call
const response = await httpClient.get('/api/s/default/stat/health');// Get the session manager for advanced session control
const sessionManager = client.getSessionManager();
// Wrap API calls with automatic authentication
const result = await sessionManager.withAuth(async () => {
return httpClient.get('/api/s/default/stat/device');
});// Create clients for different sites
const defaultSite = new UniFiClient({
baseUrl: 'https://controller.example.com:8443',
username: 'admin',
password: 'password',
site: 'default'
});
const corporateSite = new UniFiClient({
baseUrl: 'https://controller.example.com:8443',
username: 'admin',
password: 'password',
site: 'corporate'
});This library is written in TypeScript and provides comprehensive type definitions:
import { UniFiDevice, UniFiClient, DeviceConfig } from 'unifi-api-ts';
// All API responses are fully typed
const devices: UniFiDevice[] = await client.list_devices();
const clients: UniFiClient[] = await client.list_users();
// Configuration objects are also typed
const deviceConfig: DeviceConfig = {
name: 'Living Room AP',
// ... other typed properties
};Enable debug mode to see detailed request/response information:
const client = new UniFiClient({
baseUrl: 'https://unifi.example.com:8443',
username: 'admin',
password: 'password',
debug: true // Enable debug logging
});Debug output includes:
- HTTP request details (method, URL, headers)
- Request and response data
- Authentication flow
- Error details
For controllers with self-signed certificates:
const client = new UniFiClient({
baseUrl: 'https://192.168.1.1:8443',
username: 'admin',
password: 'password',
verifySsl: false // Disable SSL verification
});Note: Only disable SSL verification in trusted environments.
Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.
This project is licensed under the MIT License - see the LICENSE file for details.
- Based on the excellent PHP UniFi-API-client by Art of WiFi
- Thanks to the UniFi community for API documentation and examples
- π API Documentation
- π Issue Tracker
- π¬ Discussions
Note: This library is not officially affiliated with Ubiquiti Inc. UniFi is a trademark of Ubiquiti Inc.