> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.sophra.org/llms.txt
> Use this file to discover all available pages before exploring further.

# API Middleware for Authentication and Rate Limiting

> A Next.js middleware component for API key validation, rate limiting, and usage tracking

The API middleware component in Sophra's architecture serves as a critical gatekeeper for all incoming API requests, implementing a robust authentication mechanism based on API keys. This middleware is strategically positioned to intercept and process requests before they reach the core application logic, ensuring that only authenticated and authorized clients can access Sophra's powerful data synchronization and management capabilities.

Designed to seamlessly integrate with Next.js 14's server-side architecture, this middleware leverages the power of Edge Runtime to perform rapid authentication checks without incurring significant latency. It interacts directly with Sophra's primary database through Prisma ORM, allowing for real-time validation of API keys and enforcement of usage policies.

One of the key architectural decisions reflected in this middleware is the use of API keys as the primary authentication method for service-to-service communication. This choice offers a balance between security and performance, allowing for efficient request processing while maintaining a strong security posture. The middleware's design also facilitates easy integration of additional authentication methods in the future, such as JWT for user sessions, as outlined in Sophra's comprehensive security model.

Performance optimization is a core consideration in the middleware's implementation. By utilizing Prisma's efficient querying capabilities and implementing smart caching strategies, the middleware minimizes database lookups and reduces authentication overhead. This approach ensures that Sophra can handle high volumes of API requests without compromising on security or response times.

The middleware showcases several unique technical capabilities, including dynamic rate limiting, usage tracking, and client identification. These features not only enhance security but also provide valuable insights into API usage patterns, enabling Sophra to offer advanced analytics and adaptive learning capabilities to its clients.

## Exported Components

<CodeGroup>
  ```typescript theme={null}
  export async function middleware(request: NextRequest): Promise<NextResponse>
  ```

  ```typescript theme={null}
  export const config: {
    matcher: string
  }
  ```
</CodeGroup>

The middleware function is the primary export, responsible for processing incoming requests and applying authentication logic. The `config` object specifies the URL matcher for which this middleware should be applied.

### Middleware Function

<AccordionGroup>
  <Accordion title="Parameters">
    * `request: NextRequest` - The incoming API request object
  </Accordion>

  <Accordion title="Return Value">
    * `Promise<NextResponse>` - A promise that resolves to a NextResponse object
  </Accordion>

  <Accordion title="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
  </Accordion>
</AccordionGroup>

### Config Object

```typescript theme={null}
export const config = {
  matcher: "/api/:path*"
};
```

This configuration ensures that the middleware is applied to all routes under the `/api` path.

## Implementation Examples

<CodeGroup>
  ```typescript theme={null}
  // Example usage in a Next.js API route
  import { NextApiRequest, NextApiResponse } from 'next';

  export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    // The middleware has already run at this point
    const clientId = req.headers['x-authenticated-client'];
    const apiKeyName = req.headers['x-api-key-name'];

    // Proceed with the API logic
    res.status(200).json({ message: `Hello, ${apiKeyName} (${clientId})!` });
  }
  ```

  ```typescript theme={null}
  // Integration with Sophra's search service
  import { searchIndex } from '@/services/search';

  export default async function searchHandler(req: NextApiRequest, res: NextApiResponse) {
    const clientId = req.headers['x-authenticated-client'] as string;
    const query = req.query.q as string;

    const results = await searchIndex(query, { clientId });
    res.status(200).json(results);
  }
  ```
</CodeGroup>

## Sophra Integration Details

The middleware integrates tightly with Sophra's core systems:

1. **Database Integration**: Uses Prisma client to query the `apiKey` table for validation.
2. **Authentication Flow**: Acts as the first layer in Sophra's authentication pipeline.
3. **Usage Tracking**: Updates `lastUsedAt` and `usageCount` fields for analytics.
4. **Client Identification**: Adds client information to request headers for downstream services.

<Mermaid>
  sequenceDiagram
  participant C as Client
  participant M as Middleware
  participant P as Prisma
  participant S as Sophra Services

  C->>M: API Request
  M->>P: Validate API Key
  P-->>M: Key Status
  alt Valid Key
  M->>P: Update Usage Stats
  M->>S: Forward Request (with client info)
  S-->>C: API Response
  else Invalid Key
  M-->>C: 401 Unauthorized
  end
</Mermaid>

## Error Handling

The middleware implements comprehensive error handling:

<AccordionGroup>
  <Accordion title="Missing API Key">
    * Returns a 401 Unauthorized response
    * Includes a JSON body with an error message
  </Accordion>

  <Accordion title="Invalid API Key">
    * Returns a 401 Unauthorized response
    * Logs the invalid key attempt for security monitoring
  </Accordion>

  <Accordion title="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
  </Accordion>
</AccordionGroup>

## Data Flow

<Mermaid>
  stateDiagram-v2
  \[*] --> ExtractAPIKey
  ExtractAPIKey --> ValidateKey
  ValidateKey --> CheckRateLimit : Valid Key
  ValidateKey --> ReturnUnauthorized : Invalid Key
  CheckRateLimit --> UpdateUsage : Within Limit
  CheckRateLimit --> ReturnRateLimited : Exceeded Limit
  UpdateUsage --> AddClientInfo
  AddClientInfo --> ForwardRequest
  ForwardRequest --> \[*]
  ReturnUnauthorized --> \[*]
  ReturnRateLimited --> \[*]
</Mermaid>

## 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.

<Note>
  Performance Metrics:

  * Average response time: \< 50ms
  * 99th percentile response time: \< 200ms
  * Error rate: \< 0.1%
</Note>

## Security Implementation

<Card title="Authentication Flow" icon="lock">
  1. Extract API key from `x-api-key` header
  2. Validate key against database (active and non-expired)
  3. Check rate limiting rules
  4. Append client information to request headers
</Card>

<Card title="Data Protection" icon="shield">
  * API keys are hashed before storage
  * All database queries use parameterized statements to prevent SQL injection
  * Rate limiting protects against brute-force attacks
</Card>

## Configuration

<CodeGroup>
  ```env theme={null}
  POSTGRESQL_URL="postgresql://user:password@localhost:5432/sophra"
  REDIS_URL="redis://localhost:6379"
  API_RATE_LIMIT_ENABLED=true
  API_RATE_LIMIT_REQUESTS=100
  API_RATE_LIMIT_INTERVAL=60
  ```
</CodeGroup>

<AccordionGroup>
  <Accordion title="Environment Variables">
    * `POSTGRESQL_URL`: Connection string for the primary database
    * `REDIS_URL`: Connection string for the Redis cache (if implemented)
    * `API_RATE_LIMIT_ENABLED`: Toggle for rate limiting feature
    * `API_RATE_LIMIT_REQUESTS`: Number of allowed requests per interval
    * `API_RATE_LIMIT_INTERVAL`: Time interval for rate limiting (in seconds)
  </Accordion>

  <Accordion title="Runtime Options">
    * Configure the `matcher` in `config` object to adjust which routes use this middleware
    * Modify the `prisma` query to change API key validation logic
  </Accordion>
</AccordionGroup>
