Next.js 39: Route Handlers — Building an API
easy⏱ 5 mincoursenextjs
One function per HTTP method
A Route Handler file can export GET, POST, PUT, PATCH, DELETE, and more — one async function per verb, all in the same route.ts. Each one receives the incoming Request and must return a Response. NextResponse.json(data, { status }) is the common shortcut for JSON APIs.
// app/api/todos/route.ts
import { NextResponse } from 'next/server';
let todos = [{ id: 1, text: 'Learn Route Handlers' }];
export async function GET() {
return NextResponse.json(todos);
}
export async function POST(request: Request) {
const body = await request.json();
const todo = { id: Date.now(), text: body.text };
todos.push(todo);
return NextResponse.json(todo, { status: 201 });
}
Build the endpoint inspector
Wire the GET button to call the local GET() function and the POST button to call POST(text) with the input's value. Render the JSON response — including its status code — in the panel below. Keep export default App.
Route Handlers never ship to the client
Unlike a page component, the code inside a Route Handler runs only on the server and is never bundled into client JavaScript. That makes it the right place for database queries, API keys, and anything else that must stay off the browser.