Add API Key Validation with AI Prompts

Share

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:

Basic API Key Validation

Add API key validation to my API endpoints.

Requirements:

  1. Accept API key in the Authorization header (Bearer token) or X-API-Key header
  2. Validate the key format before database lookup
  3. Look up the key in the database to verify it's valid
  4. Return proper error responses for missing, invalid, or expired keys
  5. 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

Next.js API Key Validation

Create API key validation middleware for Next.js API routes.

For both Pages Router and App Router:

  1. Create a withApiKey higher-order function for Pages Router
  2. Create a validateApiKey helper for App Router route handlers
  3. Check the Authorization header or X-API-Key
  4. Validate against database (Supabase/Prisma/etc.)
  5. 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

Express API Key Middleware

Create Express middleware for API key validation.

Features needed:

  1. Middleware function that validates API keys
  2. Support for both header-based and query param keys
  3. Database lookup for key validation
  4. Attach user/account info to req object on success
  5. 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

Scoped API Keys

Implement scoped API keys with different permission levels.

I need:

  1. API keys with specific permissions (read, write, admin)
  2. Keys that can be limited to specific endpoints
  3. Keys with expiration dates
  4. 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

Secure Key Generation

Create a secure API key generation system.

Requirements:

  1. Generate cryptographically secure random keys
  2. Use a prefix to identify key type (e.g., pk_live_, sk_test_)
  3. Include a checksum for basic validation
  4. Hash the key before storing
  5. 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
AI Fix Prompts

Add API Key Validation with AI Prompts