API Keys
API keys are simple tokens that identify the calling application or user. They're one of the most common authentication methods for APIs.
What is an API Key?
An API key is a unique string that:
- Identifies the client making requests
- May grant access to specific resources
- Can be rate-limited or revoked
sk_live_4eC39HqLyjWDarjtT1zdp7dc
API Key Formats
Simple Random String
abc123def456ghi789
Prefixed Keys (Recommended)
sk_live_abc123... # Secret key, production
sk_test_abc123... # Secret key, testing
pk_live_abc123... # Public key, production
Prefixes help identify:
- Key type (secret vs public)
- Environment (live vs test)
Sending API Keys
In Headers (Recommended)
GET /api/users
X-API-Key: sk_live_abc123...
Or using Authorization header:
GET /api/users
Authorization: ApiKey sk_live_abc123...
In Query String (Less Secure)
GET /api/users?api_key=sk_live_abc123...
Exercise: API Key Validator
Loading JavaScript Exercise...
API Key Best Practices
1. Generate Cryptographically Secure Keys
const crypto = require('crypto');
const key = 'sk_live_' + crypto.randomBytes(24).toString('hex');
2. Store Keys Securely
// Store hashed, not plain text
const hashedKey = await bcrypt.hash(key, 10);
await db.apiKeys.create({ keyHash: hashedKey });
3. Support Key Rotation
Allow users to:
- Generate new keys
- Have multiple active keys
- Revoke old keys
4. Set Expiration Dates
{
"key": "sk_live_...",
"expiresAt": "2025-01-01T00:00:00Z",
"scopes": ["read:users", "write:orders"]
}
5. Implement Scopes
Limit what each key can do:
const keyScopes = {
'sk_live_abc': ['read:products', 'read:orders'],
'sk_live_xyz': ['read:products', 'write:products']
};
API Key vs JWT
| Feature | API Key | JWT |
|---|---|---|
| Stateless | No (DB lookup) | Yes |
| Revocation | Easy | Difficult |
| Expiration | Optional | Built-in |
| Payload | None | Custom claims |
| Best for | Server-to-server | User sessions |
Security Considerations
Never Expose Secret Keys
- Don't commit to version control
- Don't include in client-side code
- Use environment variables
Monitor Key Usage
- Log API key activity
- Alert on unusual patterns
- Detect potential leaks
Provide Key Management UI
- Dashboard to view keys
- Create/revoke functionality
- Usage statistics
Summary
API keys are:
- Simple to implement and use
- Good for identifying applications
- Need server-side storage for validation
- Best for server-to-server communication

