Improve API Error Handling and Add Rate Limiting
Description
The API routes need consistent error handling patterns and rate limiting to prevent abuse. Currently, error handling varies across routes and there is no request rate limiting beyond subscription plan quotas.
What Needs to Be Done
1. Standardize API Error Responses
- Create a shared error handler utility at
src/lib/utils/api-error.ts
- Define standard error response format:
{ error: string, code: string, status: number }
- Apply consistent error handling across all API routes in
src/app/api/
2. Add Rate Limiting
- Implement rate limiting middleware using in-memory store or Redis
- Apply to critical endpoints:
/api/generate — AI generation (most expensive)
/api/contact — Contact form (spam prevention)
/api/razorpay/create-order — Payment creation
- Rate limits by IP and/or authenticated user
- Return
429 Too Many Requests with Retry-After header
3. Input Validation
- Add Zod schema validation to all API routes
- Validate request body, query params, and path params
- Return clear validation error messages
Files to Create/Modify
- Create:
src/lib/utils/api-error.ts — Shared error utilities
- Create:
src/lib/middleware/rate-limit.ts — Rate limiting middleware
- Modify: All files in
src/app/api/ — Apply consistent patterns
Acceptance Criteria
Improve API Error Handling and Add Rate Limiting
Description
The API routes need consistent error handling patterns and rate limiting to prevent abuse. Currently, error handling varies across routes and there is no request rate limiting beyond subscription plan quotas.
What Needs to Be Done
1. Standardize API Error Responses
src/lib/utils/api-error.ts{ error: string, code: string, status: number }src/app/api/2. Add Rate Limiting
/api/generate— AI generation (most expensive)/api/contact— Contact form (spam prevention)/api/razorpay/create-order— Payment creation429 Too Many RequestswithRetry-Afterheader3. Input Validation
Files to Create/Modify
src/lib/utils/api-error.ts— Shared error utilitiessrc/lib/middleware/rate-limit.ts— Rate limiting middlewaresrc/app/api/— Apply consistent patternsAcceptance Criteria