API Route Handlers
6.1 POST /api/essearch
Location: src/app/api/essearch/route.ts
Purpose: Handles Elasticsearch voter search requests with Directus authentication and token management.
Signature:
export async function POST(req: NextRequest): Promise<NextResponse>
Request Body:
{
params: {
firstName?: string;
lastName?: string;
houseNumber?: string;
zip?: string;
county?: string;
city?: string;
order?: string;
queryFrom?: number;
querySize?: number;
};
credentials: {
name: string; // Cookie name for token
emailKey: string; // Env var key for email
endpointKey: string; // Env var key for Directus URL
passwordKey: string; // Env var key for password
};
}
Response:
{
persons: any[]; // Search results
hitsCount: number; // Number of results
totalHits: number; // Total available results
error?: string; // Error message if failed
errorCode?: number; // HTTP error code
}
Logic Flow:
-
Extract Parameters:
- Parses request body
- Extracts search params and credentials
- Gets environment variables using credential keys
-
Environment Validation:
- Checks if email, password, and Directus URL exist
- Returns 500 if missing
-
Token Management:
- Checks for existing token in cookies
- Token name from
credentials.name
-
Authentication Function:
async function authenticate(): Promise<string> {
// Creates Directus client
// Logs in with email/password
// Gets access token
// Sets HTTP-only cookie (1 hour expiration)
// Returns token
} -
API Call with Retry:
- Attempts API call with token
- On 401 Unauthorized:
- Deletes invalid token cookie
- Re-authenticates
- Retries once
- On success: Returns formatted response
- On other errors: Returns error response
-
Response Formatting:
- Maps Directus response to app format:
hits→personshits.length→hitsCounttotal.value→totalHits
- Maps Directus response to app format:
Cookie Configuration:
- HTTP-only (not accessible via JavaScript)
- Secure in production
- SameSite: strict
- Max age: 3600 seconds (1 hour)
- Path: "/"
Error Handling:
- Retries once on 401
- Returns error with status code
- Includes stack trace in development
- Logs errors to console
Security:
- Credentials stored in environment variables
- Tokens in HTTP-only cookies
- No credentials in response
- Secure flag in production