Best Practices
1. Error Handling
Always implement proper error handling for different response codes:
async function handleAPIResponse(response) {
if (response.status === 401) {
// Handle authentication errors
throw new Error('Invalid or expired API key');
} else if (response.status === 403) {
// Handle permission errors
throw new Error('Insufficient permissions or subscription required');
} else if (response.status === 429) {
// Handle rate limiting with exponential backoff
await new Promise(resolve => setTimeout(resolve, 2000));
// Retry the request
} else if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Unknown API error');
}
return await response.json();
}
2. Input Validation
Validate data client-side before sending to the API:
function validateSmartlinkData(data) {
const errors = [];
if (!data.smartlinkId) {
errors.push('Smartlink ID is required');
}
if (data.configuration?.smartlinkUrl) {
if (!/^[a-zA-Z0-9]+$/.test(data.configuration.smartlinkUrl)) {
errors.push('Smartlink URL can only contain alphanumeric characters');
}
if (data.configuration.smartlinkUrl.length > 64) {
errors.push('Smartlink URL must be 64 characters or less');
}
}
return errors;
}
3. Secure API Key Storage
// ❌ Don't store API keys in client-side code
const API_KEY = 'rlk_your_api_key_here'; // NEVER do this!
// ✅ Use environment variables on server-side
const API_KEY = process.env.SMARTLINK_API_KEY;
// ✅ For client applications, proxy through your backend
async function callSmartlinkAPI(data) {
// Call your own backend endpoint that handles the API key
return fetch('/api/smartlink-proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
}
4. Batch Operations
If updating multiple smartlinks, implement proper batching:
async function updateMultipleSmartlinks(updates) {
const results = [];
const batchSize = 5;
for (let i = 0; i < updates.length; i += batchSize) {
const batch = updates.slice(i, i + batchSize);
const batchPromises = batch.map(update =>
api.updateSmartlink(update.id, update.data)
.catch(error => ({ error: error.message, id: update.id }))
);
const batchResults = await Promise.all(batchPromises);
results.push(...batchResults);
// Add delay between batches to respect rate limits
if (i + batchSize < updates.length) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
return results;
}