GameCraftGameCraft

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 Routes

Three Routing Methods


Comparison Matrix

FeatureNext.js RoutestRPCOpenAPI/Hono
Type SafetyManualAutomatic ✨Zod schemas
Auto-completion❌ No✅ Yes❌ No
DocumentationManualAuto-generatedOpenAPI spec ✨
External Clients✅ Yes❌ TypeScript only✅ Yes
Learning CurveLowMediumMedium
Best ForWebhooks, SSRInternal APIsPublic 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

Learn More: Routing Guide


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.

Learn More: Routing Guide


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.

Learn More: Routing Guide


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_KEY

Response:

{
  "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

  1. Microservice Integration: Sync user data between services
  2. Admin Dashboards: Build system-wide monitoring tools
  3. Reporting: Generate cross-service analytics
  4. 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:

  1. Create tRPC router with same logic
  2. Update frontend to use tRPC client
  3. Test both endpoints work
  4. Remove old REST endpoint
  5. Enjoy type safety! ✨

From tRPC to OpenAPI

If you need to expose tRPC endpoints externally:

  1. Create OpenAPI route with same logic
  2. Add proper authentication
  3. Document with OpenAPI spec
  4. Keep tRPC for internal use
  5. Both can coexist

Testing

Each routing method has different testing approaches:

  • Next.js Routes: Test with NextRequest mocks
  • tRPC: Test routers directly with createCaller
  • OpenAPI: Test with Hono's app.request()

Learn More: Testing Guide


Next Steps


Resources

On this page