API Key Management and Rotation Strategies
<h2>API Key Basics</h2>
<p>API keys are simple authentication tokens used for service-to-service communication. While simpler than OAuth, they require careful management to stay secure.</p>
<h2>Generating Secure API Keys</h2>
<pre><code>import crypto from 'crypto';
export function generateAPIKey(): string {
// Generate 32 bytes of random data
const key = crypto.randomBytes(32).toString('base64url');
return sk_${key}; // Prefix for identification
}
// Store hashed version in database const apiKey = generateAPIKey(); const hashedKey = await bcrypt.hash(apiKey, 10); await APIKey.create({ userId, hashedKey, name: 'Production API' });
<h2>Key Rotation</h2>
<p>Rotate API keys regularly (every 90 days) to limit exposure:</p>
<pre><code>export async function rotateAPIKey(keyId: string) {
const newKey = generateAPIKey(); const hashedKey = await bcrypt.hash(newKey, 10);
// Create new key await APIKey.create({ userId: oldKey.userId, hashedKey, name: oldKey.name, expiresAt: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000), });
// Mark old key for deletion in 30 days (grace period) await APIKey.findByIdAndUpdate(keyId, { deprecatedAt: new Date(), expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), });
return newKey; }
<h2>Rate Limiting</h2>
<p>Protect your APIs with rate limiting:</p>
<pre><code>import rateLimit from 'express-rate-limit';
const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Limit each key to 100 requests per windowMs message: 'Too many requests from this API key', keyGenerator: (req) => req.headers['x-api-key'], });
<h2>Monitoring and Alerts</h2>
<ul>
<li>Track API key usage (requests per key)</li>
<li>Alert on unusual patterns (spike in requests)</li>
<li>Log all API key access</li>
<li>Monitor for leaked keys (GitHub, public repos)</li>
</ul>
<h2>Conclusion</h2>
<p>API keys are simple but powerful. With proper generation, storage, rotation, and monitoring, they provide secure authentication for service-to-service communication.</p>
About the Author
Sarah Chen
Cloud Infrastructure Architect
Ex-AWS Solutions Architect, 8+ years in cloud infrastructureCloud infrastructure specialist focusing on EU-compliant hosting solutions. Former AWS Solutions Architect, now helping European startups with deployment strategies.
Get notified of updates
Subscribe to receive an email when this article is updated with new information.
We'll only email you about updates to this specific article. Unsubscribe anytime.Tagged with
Related Articles
View all AuthImplementing SAML SSO for Enterprise B2B Applications
Complete guide to implementing SAML-based Single Sign-On for enterprise customers. Covers SAML flows, metadata exchange, and multi-tenant configuration.
Zero Trust Architecture for Modern Web Applications
Implement zero trust security principles in your web application. Learn continuous verification, least privilege access, and micro-segmentation.
Secure Session Management in Next.js with Redis
Best practices for managing user sessions securely in Next.js using Redis. Covers session storage, rotation, and security hardening.
Role-Based Access Control (RBAC) in React Applications
Implement robust role-based access control in React with TypeScript. Includes route protection, component-level permissions, and API authorization.
Social Login Integration: Google, GitHub, and Microsoft
Complete guide to integrating social login providers with GDPR-compliant consent flows. Includes OAuth setup for Google, GitHub, and Microsoft.
Passwordless Authentication: The Future of Login
Explore passwordless authentication with magic links, WebAuthn, and biometrics. Learn how to implement secure, user-friendly login without passwords.