# Troubleshooting Guide

Common issues and solutions when using the Lilith API.

## Authentication Issues

### Problem: "Invalid token" error
**Cause**: JWT token expired or malformed

**Solution**:
```javascript
// Check token expiration
function isTokenExpired(token) {
  if (!token) return true;

  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    return Date.now() >= payload.exp * 1000;
  } catch (error) {
    return true; // Invalid token format
  }
}

// Refresh token if expired
if (isTokenExpired(accessToken)) {
  const response = await fetch('/v1/auth/refresh', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ refresh_token: refreshToken })
  });

  const tokens = await response.json();
  accessToken = tokens.access_token;
}
```

## Rate Limiting

### Problem: "Rate limit exceeded" (HTTP 429)
**Solution**: Implement exponential backoff

```javascript
async function handleRateLimit(response) {
  if (response.status === 429) {
    const retryAfter = response.headers.get('Retry-After');
    const delay = retryAfter ? parseInt(retryAfter) * 1000 : 1000;

    console.log(`Rate limited. Waiting ${delay}ms before retry...`);
    await new Promise(resolve => setTimeout(resolve, delay));

    return true; // Should retry
  }
  return false;
}
```

## Network Issues

### Problem: Connection timeouts
**Solution**: Configure appropriate timeouts

```javascript
// Configure fetch with timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout

try {
  const response = await fetch(url, {
    ...options,
    signal: controller.signal
  });

  clearTimeout(timeoutId);
  return await response.json();
} catch (error) {
  clearTimeout(timeoutId);

  if (error.name === 'AbortError') {
    throw new Error('Request timed out');
  }

  throw error;
}
```

## Debug Mode

### Enable debug logging
```javascript
// Set environment variable
process.env.LILITH_DEBUG = 'true';

// Or use debug flag
const client = new LilithClient({
  apiKey: process.env.LILITH_API_KEY,
  debug: true
});

// Debug logging function
function debugLog(message, data) {
  if (process.env.LILITH_DEBUG === 'true') {
    console.log(`[DEBUG] ${message}`, data);
  }
}
```

## Common Error Codes

| Code | Status | Description | Solution |
|------|--------|-------------|----------|
| INVALID_TOKEN | 401 | JWT token is invalid or expired | Refresh token |
| RATE_LIMIT_EXCEEDED | 429 | Too many requests | Implement backoff |
| VALIDATION_ERROR | 400 | Request data is invalid | Check request format |
| NOT_FOUND | 404 | Resource not found | Verify endpoint URL |
| INTERNAL_ERROR | 500 | Server error | Retry request |

---

*For additional support, check the [community forum](https://community.lilith.app) or [contact support](https://support.lilith.app).*
