TL;DR
These prompts help you add proper API key validation to your endpoints. They cover validating key format, checking against a database, handling invalid keys with proper error responses, and implementing key scoping for different permission levels.
Basic API Key Validation
Use this prompt to add API key validation to your endpoints:
Add API key validation to my API endpoints.
Requirements:
- Accept API key in the Authorization header (Bearer token) or X-API-Key header
- Validate the key format before database lookup
- Look up the key in the database to verify it's valid
- Return proper error responses for missing, invalid, or expired keys
- Use timing-safe comparison to prevent timing attacks
The validation should:
- Return 401 for missing or malformed keys
- Return 403 for invalid or revoked keys
- Include rate limiting per API key
- Log failed validation attempts (without logging the actual key)
Create reusable middleware that can be applied to protected routes.
Framework-Specific Validation
Next.js API Routes
Create API key validation middleware for Next.js API routes.
For both Pages Router and App Router:
- Create a withApiKey higher-order function for Pages Router
- Create a validateApiKey helper for App Router route handlers
- Check the Authorization header or X-API-Key
- Validate against database (Supabase/Prisma/etc.)
- Return proper JSON error responses
Include:
- TypeScript types for the API key and user
- Edge runtime compatible version if needed
- Example usage for both router types
- Helper to generate new API keys with proper entropy
Express.js Middleware
Create Express middleware for API key validation.
Features needed:
- Middleware function that validates API keys
- Support for both header-based and query param keys
- Database lookup for key validation
- Attach user/account info to req object on success
- Configurable for different routes (some public, some protected)
Security requirements:
- Timing-safe string comparison
- Rate limiting per key
- Key hashing in database (don't store raw keys)
- Proper error messages that don't leak information
Create both the middleware and a key generation utility.
Advanced Validation Features
Scoped API Keys
Implement scoped API keys with different permission levels.
I need:
- API keys with specific permissions (read, write, admin)
- Keys that can be limited to specific endpoints
- Keys with expiration dates
- Keys tied to specific resources (e.g., only access their own data)
Database schema should include:
- Key hash (not raw key)
- Scopes/permissions array
- Created/expires dates
- Last used timestamp
- Associated user/account
Validation middleware should:
- Check key validity
- Verify required scopes for the endpoint
- Update last_used timestamp
- Block expired keys
Never store raw API keys: Always hash API keys before storing them in your database. When a key is generated, show it once to the user, then only store the hash. This way, if your database is compromised, the keys can't be used.
Key Generation
Create a secure API key generation system.
Requirements:
- Generate cryptographically secure random keys
- Use a prefix to identify key type (e.g., pk_live_, sk_test_)
- Include a checksum for basic validation
- Hash the key before storing
- Return the raw key only once (on creation)
Key format: prefixrandom_byteschecksum Example: sk_live_a1b2c3d4e5f6g7h8_x9y0
Provide:
- Key generation function
- Key validation function (check format and checksum)
- Key hashing function for storage
- Database migration for the keys table
Pro tip: Use key prefixes like pk_ (publishable) and sk_ (secret) to help identify key types and catch accidental exposure of secret keys in client-side code.
Should I use API keys or OAuth for authentication?
API keys are simpler and good for server-to-server communication. OAuth is better for user-facing applications where you need to authenticate users and control their access to resources.
Where should API keys be sent in requests?
The Authorization header is preferred (as Bearer token). The X-API-Key header is also common. Avoid query parameters as they can be logged in server access logs and browser history.
How often should API keys be rotated?
It depends on your security requirements. For high-security applications, rotate keys every 90 days. At minimum, rotate immediately if there's any suspicion of compromise.
Test Your API Security
Scan your API endpoints to find authentication and validation issues.
Start Free Scan