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