Customization

AI API Gateway Custom Headers

Complete guide to implementing custom HTTP headers for AI API Gateway. Learn best practices for authentication, monitoring, routing, and security through custom header configurations.

📋

Custom Headers Overview

Custom headers are essential for controlling API Gateway behavior, enabling features like authentication, rate limiting, monitoring, and request routing. They provide a flexible way to extend API Gateway functionality without modifying backend services.

Try Header Configuration

Key Benefits

  • Enhanced Security: Add authentication and authorization headers
  • Improved Monitoring: Include request IDs, timestamps, and tracing information
  • Better Routing: Use headers for A/B testing, canary deployments, and geographic routing
  • Rate Limiting: Implement custom rate limiting based on user or application headers
🔑

Common Custom Headers

Here are the most commonly used custom headers in AI API Gateway implementations:

X-API-Key
API key authentication for client applications
Bearer sk-... or API-Key abc123...
X-Request-ID
Unique identifier for request tracing and debugging
req_1234567890abcdef
X-User-ID
User identifier for multi-tenant applications
user_9876543210
X-Rate-Limit
Custom rate limiting configuration
1000/hour, 60/minute

Security Best Practices

  • Always validate and sanitize custom headers
  • Use HTTPS to prevent header interception
  • Implement proper header size limits
  • Log suspicious header patterns
  • Use signed headers for sensitive operations
⚙️

Implementation Guide

Middleware Implementation

Implement custom header middleware to inject and validate headers:

const customHeaderMiddleware = (req, res, next) => {
    // Add custom headers to request
    req.headers['X-Request-ID'] = generateRequestId();
    req.headers['X-API-Version'] = '2026-03';
    
    // Validate authentication headers
    const apiKey = req.headers['X-API-Key'];
    if (!isValidApiKey(apiKey)) {
        return res.status(401).json({ error: 'Invalid API key' });
    }
    
    // Add response headers
    res.setHeader('X-Processing-Time', Date.now() - req.startTime);
    res.setHeader('X-Rate-Limit-Remaining', calculateRateLimit(req));
    
    next();
};

// Apply middleware to API Gateway routes
app.use('/api', customHeaderMiddleware);

Header Validation Function

function validateCustomHeaders(headers) {
    const allowedHeaders = {
        'X-API-Key': '^Bearer\\s+sk-[a-zA-Z0-9]{48}$',
        'X-Request-ID': '^req_[a-f0-9]{16}$',
        'X-User-ID': '^user_[a-f0-9]{10}$',
        'X-API-Version': '^\\d{4}-\\d{2}$'
    };
    
    for (const [headerName, expectedValue] of Object.entries(allowedHeaders)) {
        if (headers[headerName]) {
            const regex = new RegExp(expectedValue);
            if (!regex.test(headers[headerName])) {
                throw new Error(`Invalid header format for ${headerName}`);
            }
        }
    }
    
    // Check for unknown custom headers
    const customHeaders = Object.keys(headers).filter(h => h.startsWith('X-'));
    for (const customHeader of customHeaders) {
        if (!allowedHeaders.hasOwnProperty(customHeader)) {
            console.warn(`Unknown custom header: ${customHeader}`);
        }
    }
}