Next.js Route Handlers: One File, Multiple Methods
Think of a Next.js Route Handler file as a dedicated API endpoint. You handle different HTTP requests by exporting functions named `GET`, `POST`, `DELETE`, etc. Use them to build API routes for form submissions or to fetch data for client-side components.
WHY IT EXISTS: Next.js Route Handlers exist to let you create server-side API endpoints directly within your app structure. This avoids the need for a separate backend server for tasks like handling forms, serving data to the client, or integrating with third-party services.
THE MENTAL MODEL: Think of a route.ts file as a switchboard for a specific URL. Each exported function named after an HTTP method (GET, POST, PUT, DELETE) is a different connection point. When a request hits that URL, Next.js directs it to the function matching its method.
HOW IT WORKS: Inside a folder in your app directory, you create a route.ts or route.js file. Within this file, you export one or more async functions. The name of each function must be an uppercase HTTP method. For example, export async function GET(request) { ... } will handle all GET requests to that route's URL. Similarly, export async function POST(request) { ... } will handle POST requests.
WHEN TO USE IT: Use Route Handlers when you need to create a backend endpoint. This is ideal for three main scenarios: first, processing form submissions from your client; second, creating an API for your client components to fetch data from; and third, building webhooks to receive data from external services.
WHEN NOT TO USE IT: Do not use Route Handlers to render HTML pages. That is the job of page.tsx. Route Handlers are specifically for returning data, typically in JSON format, using NextResponse.json(). If you need to return a UI, use a Page Component.
ONE CANONICAL EXAMPLE: To create an API endpoint at /api/users, you would create the file app/api/users/route.ts. Inside, you could write: import { NextResponse } from 'next/server'; export async function GET() { const users = [{ id: 1, name: 'Alice' }]; return NextResponse.json({ users }); }. A GET request to /api/users would then receive the JSON user data.
Read the original → nextjs.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.