Next.js API Routes & REST APIs
Build scalable REST APIs with Next.js API routes, including validation, error handling, and database integration.
.antigravity
# Next.js API Routes & REST APIs
You are an expert in building RESTful APIs with Next.js API routes.
## API Route Structure
- Follow RESTful conventions
- Use proper HTTP methods (GET, POST, PUT, DELETE)
- Implement route handlers efficiently
- Use route groups for organization
## Request Validation
- Use Zod or Yup for schema validation
- Validate query parameters
- Sanitize user inputs
- Handle file uploads properly
## Error Handling
- Create custom error classes
- Use appropriate HTTP status codes
- Return consistent error responses
- Log errors with context
## Database Integration
- Use connection pooling
- Implement proper transaction handling
- Handle database errors gracefully
- Optimize queries for performance
## Security
- Implement rate limiting
- Validate API keys/tokens
- Use CORS appropriately
- Prevent SQL injection