Guidelines for using the Lilith API effectively and securely.
Security Best Practices#
1. API Key Management#
javascript
// ❌ Don't hardcode API keys
const apiKey = 'sk-1234567890abcdef';
// ✅ Use environment variables
const apiKey = process.env.LILITH_API_KEY;
// ✅ Use configuration files (not committed to version control)
const config = require('./config.json');
const apiKey = config.apiKey;
2. Token Storage#
javascript
// ✅ Store tokens securely
class TokenManager {
constructor() {
this.token = null;
this.refreshToken = null;
this.expiresAt = null;
}
async getValidToken() {
if (this.isTokenExpired()) {
await this.refreshAccessToken();
}
return this.token;
}
isTokenExpired() {
return !this.token || Date.now() > this.expiresAt;
}
}
Error Handling#
1. Retry Logic#
javascript
async function apiCallWithRetry(url, options, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
// Rate limited - use exponential backoff
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.warn(`Attempt ${attempt} failed, retrying...`);
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
2. Response Validation#
javascript
function validateApiResponse(response, expectedFields) {
for (const field of expectedFields) {
if (!(field in response)) {
throw new Error(`Missing required field: ${field}`);
}
}
return response;
}
// Usage
const chatResponse = await makeApiCall('/v1/chat', options);
const validatedResponse = validateApiResponse(chatResponse, ['message', 'conversation_id']);
Performance Optimization#
1. Request Caching#
javascript
class ApiCache {
constructor(ttl = 300000) { // 5 minutes default
this.cache = new Map();
this.ttl = ttl;
}
async get(key, fetcher) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < this.ttl) {
return cached.data;
}
const data = await fetcher();
this.cache.set(key, { data, timestamp: Date.now() });
return data;
}
}
These best practices are based on real-world usage patterns and security requirements.