API Routing Decision Guide
Choose the right API routing method for your use case - Next.js Routes, tRPC, or OpenAPI
API Routing Decision Guide
ProductReady supports three different API routing methods. This guide helps you choose the right one for your use case.
For detailed implementation examples, see the Routing Guide.
Quick Decision Tree
Need external API access (mobile apps, third parties)?
├─ YES → Use OpenAPI/Hono REST API
└─ NO → Is this for your Next.js frontend?
├─ YES → Use tRPC for type-safe APIs
└─ NO → Special cases (webhooks, OAuth)?
└─ Use Next.js API RoutesThree Routing Methods
Next.js API Routes
Server-side routes with full Next.js features
tRPC Endpoints
Type-safe APIs for frontend-backend communication
OpenAPI REST API
Standard REST API with automatic documentation
Comparison Matrix
| Feature | Next.js Routes | tRPC | OpenAPI/Hono |
|---|---|---|---|
| Type Safety | Manual | Automatic ✨ | Zod schemas |
| Auto-completion | ❌ No | ✅ Yes | ❌ No |
| Documentation | Manual | Auto-generated | OpenAPI spec ✨ |
| External Clients | ✅ Yes | ❌ TypeScript only | ✅ Yes |
| Learning Curve | Low | Medium | Medium |
| Best For | Webhooks, SSR | Internal APIs | Public APIs, mobile |
When to Use Each Method
Use Next.js API Routes When...
- ✅ Implementing webhooks from external services (Stripe, GitHub, etc.)
- ✅ Building OAuth callbacks and authentication flows
- ✅ Handling file uploads with custom processing
- ✅ Server-side rendering with data fetching
- ✅ You need Next.js-specific features (cookies, redirects, headers)
Example Use Cases:
- Payment provider webhooks
- OAuth provider callbacks (GitHub, Google)
- Server-side file processing
- Better Auth endpoints
Use tRPC When...
- ✅ Building internal APIs for your Next.js frontend
- ✅ You want end-to-end type safety without code generation
- ✅ Working with React components that fetch/mutate data
- ✅ Need automatic type inference and auto-completion
- ✅ Your entire stack is TypeScript
Example Use Cases:
- Dashboard data fetching
- User profile updates
- Real-time subscriptions
- Internal CRUD operations
Key Benefit: Changes to backend types automatically propagate to frontend with TypeScript errors.
Use OpenAPI/Hono When...
- ✅ Building public APIs for third-party developers
- ✅ Supporting mobile apps (iOS, Android, React Native)
- ✅ Need non-TypeScript clients (Python, Go, Java)
- ✅ Want automatic OpenAPI documentation
- ✅ Building microservices with cross-service communication
- ✅ Implementing site-level administrative endpoints
Example Use Cases:
- Mobile app backends
- Public REST APIs
- Third-party integrations
- SDK generation for multiple languages
- System admin APIs for inter-service calls
Key Benefit: Industry-standard REST API with Swagger UI and OpenAPI spec for easy integration.
System Admin API (Special Case)
ProductReady includes a site-level API using OpenAPI for microservices communication with a global secret key.
Purpose
- 🔐 Secure microservices communication
- 👨💼 Administrative operations across all users
- 🔄 Service-to-service authentication
- 📊 System-wide analytics and reporting
Authentication
System admin endpoints use SYSTEM_ADMIN_API_SECRET_KEY environment variable (not user API keys):
# Required in .env
SYSTEM_ADMIN_API_SECRET_KEY="your-secure-secret-key"Security: This key grants full site access. Never commit it to version control!
Available Endpoints
List All Users
GET /api/v1/system-admin/users?limit=20&search=john&role=USER
Authorization: Bearer $SYSTEM_ADMIN_API_SECRET_KEYResponse:
{
"users": [
{
"id": "usr_123",
"name": "John Doe",
"email": "john@example.com",
"role": "USER",
"banned": false,
"createdAt": "2024-01-01T00:00:00.000Z"
}
],
"total": 42,
"limit": 20,
"offset": 0
}Use Cases
- Microservice Integration: Sync user data between services
- Admin Dashboards: Build system-wide monitoring tools
- Reporting: Generate cross-service analytics
- Data Migration: Bulk operations across users
Example: Python Microservice
import os
import requests
API_KEY = os.environ['SYSTEM_ADMIN_API_SECRET_KEY']
BASE_URL = 'https://api.yourdomain.com/api/v1'
headers = {'Authorization': f'Bearer {API_KEY}'}
# Get all users
response = requests.get(
f'{BASE_URL}/system-admin/users',
params={'limit': 100},
headers=headers
)
for user in response.json()['users']:
print(f"{user['email']} - {user['role']}")API Reference: System Admin Endpoints
Common Scenarios
Scenario 1: Building a User Dashboard
Best Choice: tRPC
Why:
- Internal use only
- Type-safe data fetching
- React Query integration
- No need for external clients
Scenario 2: Mobile App Backend
Best Choice: OpenAPI/Hono
Why:
- Need REST endpoints
- iOS/Android clients
- Public API documentation
- Non-TypeScript clients
Scenario 3: Payment Webhooks
Best Choice: Next.js API Routes
Why:
- Webhook from external service
- Signature verification needed
- Next.js middleware useful
- One-off endpoint
Scenario 4: Cross-Service User Sync
Best Choice: System Admin API (OpenAPI)
Why:
- Service-to-service communication
- Global authentication
- System-wide operations
- Administrative access
Anti-Patterns
❌ Don't
- Don't use tRPC for public APIs or mobile apps
- Don't use OpenAPI for internal Next.js frontend APIs (use tRPC instead)
- Don't use Next.js routes for regular CRUD operations (use tRPC)
- Don't expose system admin key to frontend clients
- Don't mix authentication types - user keys vs system admin key
✅ Do
- Use tRPC as your default for internal APIs
- Use OpenAPI when you need external access or documentation
- Use Next.js routes only for special cases (webhooks, OAuth)
- Keep system admin API for backend services only
- Document all public APIs with OpenAPI specs
Migration Guide
From REST to tRPC
If you have existing REST endpoints for internal use:
- Create tRPC router with same logic
- Update frontend to use tRPC client
- Test both endpoints work
- Remove old REST endpoint
- Enjoy type safety! ✨
From tRPC to OpenAPI
If you need to expose tRPC endpoints externally:
- Create OpenAPI route with same logic
- Add proper authentication
- Document with OpenAPI spec
- Keep tRPC for internal use
- Both can coexist
Testing
Each routing method has different testing approaches:
- Next.js Routes: Test with
NextRequestmocks - tRPC: Test routers directly with
createCaller - OpenAPI: Test with Hono's
app.request()
Next Steps
- Routing Guide - Detailed implementation examples
- API Reference - Complete API documentation
- Authentication - Secure your APIs
- Testing - Test your endpoints