Exported Components
config
object specifies the URL matcher for which this middleware should be applied.
Middleware Function
Parameters
Parameters
request: NextRequest
- The incoming API request object
Return Value
Return Value
Promise<NextResponse>
- A promise that resolves to a NextResponse object
Functionality
Functionality
- Extracts the API key from the request headers
- Validates the API key against the database
- Checks for rate limiting (if configured)
- Updates usage statistics
- Adds authenticated client information to request headers
Config Object
/api
path.
Implementation Examples
Sophra Integration Details
The middleware integrates tightly with Sophra’s core systems:- Database Integration: Uses Prisma client to query the
apiKey
table for validation. - Authentication Flow: Acts as the first layer in Sophra’s authentication pipeline.
- Usage Tracking: Updates
lastUsedAt
andusageCount
fields for analytics. - Client Identification: Adds client information to request headers for downstream services.
Error Handling
The middleware implements comprehensive error handling:Missing API Key
Missing API Key
- Returns a 401 Unauthorized response
- Includes a JSON body with an error message
Invalid API Key
Invalid API Key
- Returns a 401 Unauthorized response
- Logs the invalid key attempt for security monitoring
Database Errors
Database Errors
- Catches and logs any Prisma-related errors
- Returns a 500 Internal Server Error to the client
- Triggers an alert in Sophra’s monitoring system
Data Flow
Performance Considerations
- Caching: Implement a Redis cache for frequently used API keys to reduce database lookups.
- Batch Updates: Aggregate usage statistics and perform batch updates to minimize database writes.
- Edge Computation: Leverage Next.js Edge Runtime for faster request processing.
Performance Metrics:
- Average response time: < 50ms
- 99th percentile response time: < 200ms
- Error rate: < 0.1%
Security Implementation
Authentication Flow
- Extract API key from
x-api-key
header - Validate key against database (active and non-expired)
- Check rate limiting rules
- Append client information to request headers
Data Protection
- API keys are hashed before storage
- All database queries use parameterized statements to prevent SQL injection
- Rate limiting protects against brute-force attacks
Configuration
Environment Variables
Environment Variables
POSTGRESQL_URL
: Connection string for the primary databaseREDIS_URL
: Connection string for the Redis cache (if implemented)API_RATE_LIMIT_ENABLED
: Toggle for rate limiting featureAPI_RATE_LIMIT_REQUESTS
: Number of allowed requests per intervalAPI_RATE_LIMIT_INTERVAL
: Time interval for rate limiting (in seconds)
Runtime Options
Runtime Options
- Configure the
matcher
inconfig
object to adjust which routes use this middleware - Modify the
prisma
query to change API key validation logic