Security Best Practices
Comprehensive security guidelines to protect your API integrations and ensure safe usage of APIVerve services.
API Key Security
Secure Key Storage
Proper API key storage is critical for maintaining security:
- Store API keys in environment variables or secure key management systems
- Use encrypted configuration files for production environments
- Implement proper access controls for key storage locations
- Use secrets management tools (AWS Secrets Manager, Azure Key Vault, etc.)
Never Expose Keys
Avoid these common mistakes that can compromise your API keys:
- Never hardcode API keys in source code
- Don't include keys in client-side JavaScript or mobile apps
- Avoid storing keys in public repositories or version control
- Don't log API keys in application logs
- Never share keys in documentation, emails, or chat messages
// ❌ BAD: Hardcoded key
const API_KEY = 'sk_live_1234567890abcdef';
// ✅ GOOD: Environment variable
const API_KEY = process.env.APIVERVE_API_KEY;
// ✅ BETTER: Key validation
const API_KEY = process.env.APIVERVE_API_KEY;
if (!API_KEY) {
throw new Error('APIVERVE_API_KEY environment variable is required');
}
// ✅ BEST: Secure key service
const keyService = new SecureKeyService();
const API_KEY = await keyService.getApiKey('apiverve');
Network Security
HTTPS Communication
All APIVerve APIs enforce HTTPS communication. Ensure your applications properly validate SSL certificates:
// Node.js - Ensure SSL verification is enabled (default)
const https = require('https');
const options = {
hostname: 'api.apiverve.com',
port: 443,
path: '/v1/endpoint',
method: 'GET',
headers: {
'X-API-Key': process.env.APIVERVE_API_KEY
},
// Ensure certificate validation (default: true)
rejectUnauthorized: true
};
// Python - Verify SSL certificates
import requests
response = requests.get(
'https://api.apiverve.com/v1/endpoint',
headers={'X-API-Key': os.getenv('APIVERVE_API_KEY')},
verify=True # Verify SSL certificates (default: True)
)
IP Whitelisting
For enhanced security, consider implementing IP address restrictions:
Configure your API keys to only work from specific IP addresses or CIDR blocks. This adds an additional layer of security if your API key is compromised.
Request Security
Input Validation
Always validate and sanitize data before sending it to APIs:
function validateAndSanitizeInput(userInput) {
// Validate input format
if (typeof userInput !== 'string' || userInput.length > 1000) {
throw new Error('Invalid input format');
}
// Sanitize special characters
const sanitized = userInput
.replace(/[<>]/g, '') // Remove potential HTML
.trim();
// Additional validation based on your use case
const urlPattern = /^https?:\/\/.+/;
if (!urlPattern.test(sanitized)) {
throw new Error('Invalid URL format');
}
return sanitized;
}
// Use validated input in API calls
const validatedUrl = validateAndSanitizeInput(userProvidedUrl);
const response = await fetch('https://api.apiverve.com/v1/screenshot', {
method: 'POST',
headers: {
'X-API-Key': process.env.APIVERVE_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({ url: validatedUrl })
});
Request Size Limits
Implement appropriate request size limits to prevent abuse:
// Express.js middleware example
const express = require('express');
const app = express();
// Limit request body size
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ limit: '1mb', extended: true }));
// Custom size validation
function validateRequestSize(req, res, next) {
const contentLength = req.get('Content-Length');
if (contentLength && parseInt(contentLength) > 1048576) { // 1MB
return res.status(413).json({ error: 'Request too large' });
}
next();
}
Rate Limiting & Monitoring
Client-Side Rate Limiting
Implement client-side rate limiting to respect API limits and improve reliability:
class APIRateLimiter {
constructor(requestsPerMinute = 60) {
this.requestsPerMinute = requestsPerMinute;
this.requests = [];
}
async makeRequest(url, options) {
await this.waitIfNeeded();
try {
const response = await fetch(url, {
...options,
headers: {
'X-API-Key': process.env.APIVERVE_API_KEY,
...options.headers
}
});
// Handle rate limit headers
const remaining = response.headers.get('X-RateLimit-Remaining');
const resetTime = response.headers.get('X-RateLimit-Reset');
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After') || 60;
await this.sleep(retryAfter * 1000);
return this.makeRequest(url, options); // Retry
}
return response;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
async waitIfNeeded() {
const now = Date.now();
const oneMinuteAgo = now - 60000;
// Remove requests older than 1 minute
this.requests = this.requests.filter(time => time > oneMinuteAgo);
// Wait if we've hit the limit
if (this.requests.length >= this.requestsPerMinute) {
const oldestRequest = Math.min(...this.requests);
const waitTime = 60000 - (now - oldestRequest);
await this.sleep(waitTime);
return this.waitIfNeeded();
}
this.requests.push(now);
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
Security Checklist
Use this checklist to ensure you've implemented all essential security measures:
Was this page helpful?
Help us improve our documentation