Topic 42 of 47
API GET & POST Methods Integration
Overview
Route Handlers (API routes in the App Router) allow you to handle different HTTP methods (GET, POST, PUT, DELETE) within the same `route.ts` file by exporting named functions.
Syntax
tsx
// app/api/products/route.ts
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
// Handle GET requests (fetching data)
const products = await db.getProducts();
return NextResponse.json({ products });
}
export async function POST(request: Request) {
// Handle POST requests (creating data)
const body = await request.json(); // Parse the request body
const newProduct = await db.createProduct(body);
return NextResponse.json(newProduct, { status: 201 });
}Common Pitfalls
- By default, GET handlers in Route Handlers are statically cached at build time if they don't use dynamic functions (like reading headers or cookies). To prevent this, use `export const dynamic = 'force-dynamic';`.
- You cannot have a `route.ts` (API route) and a `page.tsx` (UI route) in the exact same folder level. They will conflict.
Real-World Example
Extracting query parameters in a GET handler and validating body in a POST handler:
example
tsx
// app/api/search/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
// NextRequest provides a handy nextUrl object for query params
const searchParams = request.nextUrl.searchParams;
const query = searchParams.get('q');
if (!query) {
return NextResponse.json({ error: 'Query required' }, { status: 400 });
}
const results = await db.search(query);
return NextResponse.json(results);
}