GET and POST Handlers
Handle different HTTP methods and read the request body or query parameters.
Syntax
export async function POST(request: Request) { const body = await request.json(); }Each exported function maps to one HTTP method. A GET handler often reads query parameters, while a POST handler reads the JSON body of the request.
Reading input
- Query string:
new URL(request.url).searchParams. - JSON body:
await request.json().
Example
import { NextResponse } from 'next/server';
// GET /api/search?q=next
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const q = searchParams.get('q');
return NextResponse.json({ query: q });
}
// POST /api/users with a JSON body
export async function POST(request: Request) {
const body = await request.json();
return NextResponse.json({ created: body }, { status: 201 });
}When to use it
- A GET handler returns a paginated list of users from the database, reading the page query parameter from the URL.
- A POST handler reads a JSON body from a subscription form and saves the email to the database.
- An API route exports both GET and POST so the same URL can list resources and create new ones.
More examples
GET with query parameters
req.nextUrl.searchParams provides typed access to URL query parameters in a GET handler.
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(req: NextRequest) {
const page = req.nextUrl.searchParams.get('page') ?? '1';
const users = await db.user.findMany({ skip: (Number(page) - 1) * 10, take: 10 });
return NextResponse.json(users);
}POST reading JSON body
req.json() deserialises the request body, enabling POST handlers to accept and persist structured data.
// app/api/subscribe/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function POST(req: NextRequest) {
const { email } = await req.json();
await db.subscriber.create({ data: { email } });
return NextResponse.json({ success: true }, { status: 201 });
}Combined GET and POST on one route
A single route.ts file can export multiple HTTP method handlers to support REST-style resource endpoints.
// app/api/posts/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET() {
const posts = await db.post.findMany();
return NextResponse.json(posts);
}
export async function POST(req: NextRequest) {
const body = await req.json();
const post = await db.post.create({ data: body });
return NextResponse.json(post, { status: 201 });
}
Discussion