xAdmin Integration Guide
Step-by-step integration examples for different platforms and languages.
Cloudflare Workers
Best for: Services deployed on Cloudflare Workers
Advantage: Internal network calls with zero public network latency (< 1ms), no TLS handshake overhead
Step 1: Configure wrangler.toml
Add the service binding to your project's wrangler.toml:
[[services]]
binding = "XADMIN" # Variable name used in code
service = "xadmin" # xAdmin service name in Cloudflare
# environment = "production" # Optional: specify environmentStep 2: TypeScript Implementation
// Environment interface definition
interface Env {
XADMIN: Fetcher;
}
export default {
async fetch(req: Request, env: Env): Promise<Response> {
// 1. Extract token from client request
const token = req.headers.get('Authorization');
if (!token) {
return new Response('Unauthorized: Missing Token', { status: 401 });
}
try {
// 2. Call xAdmin for authentication
// Service Binding calls are internal and extremely fast
const authResponse = await env.XADMIN.fetch('http://internal/v1/verify', {
method: 'POST',
headers: {
'Authorization': token, // Pass through the Bearer token
'Content-Type': 'application/json'
},
body: JSON.stringify({ count: 1 }) // Optional: consumption multiplier
});
// 3. Handle authentication result
if (authResponse.status !== 200) {
const errorText = await authResponse.text();
return new Response(errorText, {
status: authResponse.status,
headers: { 'Content-Type': 'application/json' }
});
}
// 4. Authentication successful: execute core business logic
// const result = await runBusinessLogic(req);
return new Response('Business Response Data', { status: 200 });
} catch (err) {
console.error('Auth Service Error:', err);
return new Response('Internal Auth Error', { status: 500 });
}
}
}External HTTP API
Best for: Services running in Docker containers, VMs, or other cloud providers
Method: Standard HTTP RESTful API calls
Python
import requests
def process_request(user_token: str):
auth_url = "https://api.xadmin.com/v1/verify"
try:
response = requests.post(
auth_url,
headers={"Authorization": f"Bearer {user_token}"},
json={"count": 1}, # Optional
timeout=5
)
except requests.exceptions.RequestException:
return {"error": "Auth Service Unavailable"}, 500
if response.status_code == 200:
# ✅ Verification successful
return run_business_logic()
elif response.status_code == 403:
# ❌ Verification failed
return response.json(), 403
else:
return {"error": "Unauthorized"}, 401Node.js
const axios = require('axios');
async function checkAuth(token) {
try {
const response = await axios.post(
'https://api.xadmin.com/v1/verify',
{ count: 1 },
{ headers: { 'Authorization': `Bearer ${token}` } }
);
return { success: true, balance: response.data.balance };
} catch (error) {
if (error.response) {
console.error('Auth Failed:', error.response.data);
return { success: false, error: error.response.data };
}
return { success: false, error: 'Service unavailable' };
}
}Go
package main
import (
"bytes"
"encoding/json"
"net/http"
"time"
)
type VerifyRequest struct {
Count int `json:"count"`
}
type VerifyResponse struct {
Status string `json:"status"`
Balance int64 `json:"balance"`
ExpiresAt *int64 `json:"expires_at"`
}
func verifyToken(token string) (*VerifyResponse, error) {
client := &http.Client{Timeout: 5 * time.Second}
body, _ := json.Marshal(VerifyRequest{Count: 1})
req, _ := http.NewRequest("POST", "https://api.xadmin.com/v1/verify", bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result VerifyResponse
json.NewDecoder(resp.Body).Decode(&result)
return &result, nil
}Integration Patterns
Pattern A: API Gateway Interceptor
Insert verification before executing business logic:
- User request → Your API (
/api/generate) - Interceptor sends POST to
xAdmin/v1/verify(with token)- Returns 200: Continue with business logic
- Returns 403: Reject immediately, return "Quota Exceeded"
- Business code remains agnostic to billing logic
Pattern B: Client Application (Heartbeat + Action)
Model: Heartbeat monitoring + triggered billing
- Startup Check: Call
Verify?dry_run=trueto check expiration/ban status - Periodic Heartbeat: Call
Verify?dry_run=trueevery 5-10 minutes - Feature Billing: Call
Verify(without dry_run) when user triggers a paid feature
Best Practices
1. Decouple Billing from Business
Developers should not hardcode pricing. Rates are configured in the xAdmin dashboard:
- Set "GPT-4" product cost to 10 points
- xAdmin automatically deducts based on token's associated product
- Business code requires zero changes
2. Fail-Fast on Auth Errors
If /v1/verify returns non-200 status, immediately terminate processing. Never consume GPU/CPU resources after authentication failure.
3. Token Security
- Always use HTTPS for transmission
- Never append tokens to URL parameters (e.g.,
?token=...)—they persist in browser history - Always send tokens in the
Authorizationheader
FAQ
Q1: Will verification slow down my service?
Extremely fast. xAdmin uses L1 (memory) + L2 (KV) two-tier caching:
- Hot data (99% of requests): Direct memory hit, latency < 1ms
- Service Binding: Internal network call, no TLS handshake overhead
Q2: How do I implement different billing rates?
No need to specify amounts in requests. Configure Product rates (Cost) in the xAdmin dashboard:
- Example: Set "GPT-4" product rate to 10 Points
- xAdmin automatically deducts based on the token's associated product
- Business code remains unchanged—fully decoupled
Q3: Can I test in local development?
Yes. Use wrangler dev --remote with correctly configured wrangler.toml to connect to the remote xAdmin service.