ReviseAlgo Logo

Data Fetching

Route Handlers

Learn how Route Handlers create HTTP endpoints in the App Router for APIs, webhooks, uploads, and streaming responses.

## 1. Learning Objectives By the end of this lesson, you will be able to: - Create HTTP endpoints with `route.ts`. - Implement common methods like `GET` and `POST`. - Decide when Route Handlers are better than Server Actions. - Return JSON responses and status codes. Difficulty: Beginner. ## 2. Prerequisites - App Router file conventions. - HTTP methods. - Basic JSON handling. ## 3. Overview Route Handlers are App Router files named `route.ts` that define HTTP endpoints. They are useful for public APIs, webhooks, uploads, integrations, and non-UI responses. ## 4. Why This Topic Matters Not every server operation belongs inside a page. External systems need stable endpoints, mobile apps may call APIs, and webhooks need URLs that return precise HTTP responses. ## 5. Real-World Analogy A Route Handler is like a service counter. It does not show the whole store; it receives a specific request, performs a task, and returns a clear response. ## 6. Core Concepts | Concept | Meaning | |---|---| | `route.ts` | App Router file that defines an HTTP endpoint. | | Method export | Named function like `GET`, `POST`, `PUT`, or `DELETE`. | | `Request` | Web standard request object. | | `Response` | Web standard response object. | | `NextResponse` | Next.js helper for JSON, redirects, and cookies. | ## 7. Syntax & API Reference
## 8. Visual Diagram
## 9. Live Example - Full Working Code
What just happened? A `POST /api/feedback` request can submit JSON and receive a structured response. ## 10. Interactive Playground Try this: - Create `app/api/health/route.ts`. - Call it from the browser or `curl`. - Add a `POST` handler and validate the request body. ## 11. Common Mistakes | Mistake | Why It Happens | Correct Approach | |---|---|---| | Naming the file `page.tsx` | Pages render UI. | Use `route.ts` for endpoints. | | Returning plain objects | Route Handlers must return `Response`. | Use `Response.json()` or `NextResponse.json()`. | | Skipping validation | Internal examples feel trusted. | Validate all external input. | ## 12. Best Practices - Use Route Handlers for webhooks and external APIs. - Validate request method, body, auth, and content type. - Keep secrets on the server. - Return precise status codes. - Avoid duplicating business logic between handlers and actions. ## 13. Browser Compatibility | Feature | Browser Impact | Notes | |---|---|---| | Route Handler | Server endpoint | Any HTTP client can call it. | | JSON response | Broad support | Standard HTTP. | | Webhooks | External service dependent | Must validate signatures. | ## 14. Interview Questions **Easy:** What file creates an App Router endpoint? Answer: `route.ts`. **Medium:** When should you use a Route Handler instead of a Server Action? Answer: Use Route Handlers for public APIs, webhooks, uploads, and clients outside the React app. **Hard:** Why validate webhook signatures in Route Handlers? Answer: Webhook URLs are public endpoints, so signature validation proves the request came from the expected provider. ## 15. Debugging Exercise Broken snippet:
Solution Return a `Response`, for example `return Response.json({ ok: true })`. ## 16. Practice Exercises - Easy: Build `/api/health`. - Medium: Build a `POST /api/contact` endpoint. - Hard: Add request validation and status-specific error responses. ## 17. Scenario-Based Challenge Stripe needs to call your app after payment succeeds. Server Action or Route Handler? Walkthrough Use a Route Handler because Stripe is an external service calling an HTTP endpoint. Validate the webhook signature before trusting the event. ## 18. Quick Quiz 1. What file name creates a Route Handler? Answer: `route.ts`. 2. What function handles GET requests? Answer: `GET`. 3. Should handlers return plain objects? Answer: No. 4. What helper returns JSON? Answer: `Response.json()` or `NextResponse.json()`. 5. Are Route Handlers useful for webhooks? Answer: Yes. ## 19. Summary & Key Takeaways - Route Handlers create App Router HTTP endpoints. - Export functions named by HTTP method. - Return `Response` objects. - Use them for APIs, webhooks, uploads, and integrations. - Validate all external input. ## 20. Cheat Sheet | Need | Route Handler? | |---|---| | Webhook URL | Yes | | Form mutation inside app | Maybe Server Action | | Public JSON API | Yes | | Button click state | No | | File upload endpoint | Yes | ## 21. Further Reading - Next.js Docs: Route Handlers. - MDN: Request. - MDN: Response. ## 22. Next Lesson Preview Next, you will learn Server Actions for mutations that are called directly from React forms and components.