Skip to content

Improve API Error Handling and Add Rate Limiting #120

Description

@Suraj-kumar00

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

  • Consistent error response format across all APIs
  • Rate limiting on generation, contact, and payment endpoints
  • Zod validation on all API inputs
  • Proper HTTP status codes (400, 401, 403, 404, 429, 500)
  • No sensitive information leaked in error responses

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestrefactorCode restructuring without behavior change

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions