GET request handlers
This page explains how to implement GET request handlers in Next.js route handlers.
Understanding route handlers
Route handlers allow you to create custom API endpoints in your Next.js application. The GET handler is one of the most common types, used to retrieve data from your server.
Creating a GET handler
To create a GET request handler:
- Create a
route.ts
file in your route segment - Export an async function named
GET
- Return a
Response
object
export async function GET() { const comments = [ { id: 1, text: "First comment" }, { id: 2, text: "Second comment" }, ];
return Response.json(comments);}
Response formats
The handler can return data in different formats:
// JSON responsereturn Response.json(data);
// Text responsereturn new Response("Hello");
// HTML responsereturn new Response("<h1>Hello</h1>", { headers: { "Content-Type": "text/html" },});
Good to know
- Route handlers only work in the
app
directory - The function name must match the HTTP method (GET, POST, etc.)
- Handlers receive the Request object as their first parameter