Architecture – API Routes

Understanding backend functionality with route.ts files

What Are API Routes?

API routes are the "behind-the-scenes" functionality of your app. These are files named route.ts that handle things people don't see directly but are essential for your app to work.

Key concept: While pages (page.tsx) are what users see, API routes (route.ts) are what your app does in the background.

Think of API routes as:

The place where your app does the behind-the-scenes work: talk to other services, save or fetch data, and make decisions.

When to Use API Routes

You use API routes when you want to make something that requires server-side processing:

šŸ”Œ Using Other Services

Examples:

  • Generating an AI image with Replicate or OpenAI
  • Fetching real-time data (weather, stock prices, crypto prices)
  • Using tools like Google Maps, Stripe payments, or email services
  • Connecting to crypto wallet providers like Privy or Dynamic
  • Integrating with third-party APIs like Twitter, Discord, or DoorDash

🧮 Performing Logic/Calculations

Examples:

  • Checking if a user is allowed to do something (authorization)
  • Filtering, sorting, or processing data
  • Generating scores or results based on input
  • Image manipulation or file processing
  • Complex calculations that shouldn't happen in the browser

šŸ’¾ Storing or Updating Information

Examples:

  • Saving user messages, scores, profiles, or content to a database
  • Updating user preferences or settings
  • Creating, editing, or deleting records
  • File uploads and storage management

API Route Structure

[folder-name]/route.ts

Just like pages, API routes follow a folder-based structure. The difference is they use route.ts instead of page.tsx.

API route structure example:

app/
ā”œā”€ā”€ api/
│   ā”œā”€ā”€ users/
│   │   └── route.ts              // /api/users
│   ā”œā”€ā”€ auth/
│   │   ā”œā”€ā”€ login/
│   │   │   └── route.ts         // /api/auth/login
│   │   └── signup/
│   │       └── route.ts         // /api/auth/signup
│   └── webhooks/
│       └── stripe/
│           └── route.ts         // /api/webhooks/stripe

URL Mapping

API routes are accessible at /api/[folder-structure]

app/api/users/route.ts → yoursite.com/api/users

When NOT to Use API Routes

You don't use route.ts when something is only for the frontend (what users see and interact with):

āŒ Don't use API routes for:

  • Changing button colors or layout
  • Showing/hiding elements on the page
  • Form validation that happens in the browser
  • Animations and visual effects
  • Client-side navigation and routing

āœ… Use API routes for:

  • Anything that needs to happen on the server
  • Operations that require API keys or secrets
  • Database operations
  • Third-party service integrations
  • Authentication and authorization

Common API Route Examples

šŸ“ /api/posts/route.ts

Handles blog posts or content management:

  • GET: Fetch all posts
  • POST: Create a new post
  • PUT: Update existing post
  • DELETE: Remove a post

šŸ‘¤ /api/auth/login/route.ts

Handles user authentication:

  • Verify user credentials
  • Create authentication tokens
  • Set secure cookies
  • Return user data

šŸ’³ /api/payments/route.ts

Handles payment processing:

  • Create payment intents with Stripe
  • Process payment confirmations
  • Handle subscription management
  • Update payment status in database

šŸ¤– /api/ai/generate/route.ts

Handles AI integrations:

  • Send prompts to OpenAI or other AI services
  • Process and format AI responses
  • Handle rate limiting and errors
  • Save results to database

API Route Best Practices

āœ… Do This

  • Use environment variables for API keys and secrets
  • Validate input data before processing
  • Handle errors gracefully with proper status codes
  • Use descriptive folder names for organization
  • Implement proper authentication where needed

āŒ Avoid This

  • Don't expose sensitive data or API keys
  • Don't trust user input without validation
  • Don't put business logic in page components
  • Don't ignore error handling
  • Don't make API routes publicly accessible if they shouldn't be

šŸŽÆ Security Tips

  • Always validate and sanitize input data
  • Use CORS headers appropriately
  • Implement rate limiting for public APIs
  • Use HTTPS in production
  • Log important events for monitoring