Next.js Zero to Advanced #9: Building a REST API with Route Handlers
In Part 8 DigiStore admins started managing products through forms and Server Actions. Server Actions are great for our own Next.js UI, but they are not designed to be called by other applications. What if a mobile app, a product-import script, or a partner wants to read the catalog later? They need a REST API with clear URLs, JSON, and standard HTTP status codes.
In Part 9 we build that API with Route Handlers: app/api/products/route.ts for GET (list) and POST, and app/api/products/[id]/route.ts for GET, PATCH, and DELETE. We reuse parseProductQuery and getProducts from Part 7 and productSchema from Part 8, then test everything with curl.
Important: like the Server Actions in Part 8, the POST, PATCH, and DELETE endpoints in this part are not protected yet. Part 10 adds
requireAdmin(). Do not deploy before then.
Meet Route Handlers
A Route Handler is a route.ts file inside the app folder. It exports functions named after HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS). Each function receives a standard Web Request (or a NextRequest, which adds helpers such as nextUrl) and must return a Response.
- A folder cannot contain both
page.tsxandroute.ts. That is why our API lives underapp/api/. - Methods you do not export are answered with
405 Method Not Allowedautomatically. - For dynamic routes,
paramsin the second argument is a Promise, just like in pages. - With Cache Components (Part 7), a
GETthat reads the request (such as the query string) runs per request. Other methods are never cached.
Our endpoint design:
GET /api/products list (q, category, page)
POST /api/products create a product
GET /api/products/:id product detail
PATCH /api/products/:id partial update
DELETE /api/products/:id delete a productPreparation: a Select and JSON Helpers
The API returns more product data than a product card does, but still through an explicit select. Add this to lib/products.ts:
// lib/products.ts (add)
export const productApiSelect = {
id: true,
slug: true,
title: true,
description: true,
price: true,
category: true,
imageUrl: true,
published: true,
createdAt: true,
updatedAt: true,
} satisfies Prisma.ProductSelectThen create lib/api.ts with two small helpers. jsonError gives errors a consistent shape, { "error": "..." }. readJsonBody makes sure the body really is JSON.
// lib/api.ts
export function jsonError(message: string, status: number, extra?: Record<string, unknown>) {
return Response.json({ error: message, ...extra }, { status })
}
type JsonBodyResult = { ok: true; body: unknown } | { ok: false; response: Response }
export async function readJsonBody(request: Request): Promise<JsonBodyResult> {
const contentType = request.headers.get('content-type') ?? ''
if (!contentType.includes('application/json')) {
return { ok: false, response: jsonError('Content-Type harus application/json', 415) }
}
try {
return { ok: true, body: await request.json() }
} catch {
return { ok: false, response: jsonError('Body bukan JSON yang valid', 400) }
}
}Requiring Content-Type: application/json has a security benefit too. An HTML form on another site cannot send that content type without CORS permission, so it adds a layer of CSRF protection once we use a login cookie in Part 10.
GET and POST: /api/products
GET: list products
// app/api/products/route.ts
import type { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
import { prisma } from '@/lib/prisma'
import { jsonError, readJsonBody } from '@/lib/api'
import { getPrismaErrorCode } from '@/lib/db-errors'
import { getProducts, parseProductQuery, productApiSelect } from '@/lib/products'
import { productSchema, toFieldErrors } from '@/lib/validation'
// GET /api/products?q=next&category=EBOOK&page=1
export async function GET(request: NextRequest) {
const query = parseProductQuery(Object.fromEntries(request.nextUrl.searchParams))
const { items, total, totalPages } = await getProducts(query)
return Response.json({
data: items,
meta: { page: query.page, total, totalPages },
})
}request.nextUrl.searchParams is a URLSearchParams. Object.fromEntries turns it into a plain object so the same parseProductQuery used by the /products page can process it. Query validation and the products-tagged cache come along for free. One source of logic for two entry points: the page and the API.
POST: create a product
// app/api/products/route.ts (continued)
// POST /api/products
export async function POST(request: NextRequest) {
// TODO(Part 10): await requireAdmin() and return 401/403 when it fails.
// Until then this endpoint is PUBLIC. Do not deploy it yet.
const result = await readJsonBody(request)
if (!result.ok) return result.response
const parsed = productSchema.safeParse(result.body)
if (!parsed.success) {
return jsonError('Validasi gagal', 400, { fieldErrors: toFieldErrors(parsed.error) })
}
try {
const product = await prisma.product.create({
data: parsed.data,
select: productApiSelect,
})
revalidateTag('products', { expire: 0 })
return Response.json(
{ data: product },
{ status: 201, headers: { Location: `/api/products/${product.id}` } },
)
} catch (error) {
if (getPrismaErrorCode(error) === 'P2002') {
return jsonError('Slug sudah dipakai produk lain', 409)
}
console.error('POST /api/products failed', error)
return jsonError('Terjadi kesalahan pada server', 500)
}
}The flow mirrors the Server Action, but the outcome is an HTTP status:
- Body is not JSON β 400; wrong content type β 415.
- zod validation fails β 400 with
fieldErrors. Unknown fields (such asid) are stripped by zod, so clients cannot choose their own IDs. - Duplicate slug β 409 Conflict.
- Success β 201 Created with a
Locationheader pointing to the new product. - Anything else β 500 with a generic message. Details go to the server log only.
Why revalidateTag instead of updateTag as in Part 8? updateTag can only be called from Server Actions. In Route Handlers we use revalidateTag(tag, profile). The recommended 'max' profile serves stale data while refreshing in the background. That suits a catalog, but when testing with curl you might see old data on the first GET. So we use { expire: 0 }, which expires the cache immediately and guarantees the next request gets fresh data.
GET, PATCH, DELETE: /api/products/[id]
// app/api/products/[id]/route.ts
import type { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
import { prisma } from '@/lib/prisma'
import { jsonError, readJsonBody } from '@/lib/api'
import { getPrismaErrorCode } from '@/lib/db-errors'
import { productApiSelect } from '@/lib/products'
import { productSchema, toFieldErrors } from '@/lib/validation'
type Context = { params: Promise<{ id: string }> }
const productPatchSchema = productSchema.partial()
// GET /api/products/:id
export async function GET(_request: NextRequest, { params }: Context) {
const { id } = await params
const product = await prisma.product.findUnique({
where: { id, published: true },
select: productApiSelect,
})
if (!product) return jsonError('Produk tidak ditemukan', 404)
return Response.json({ data: product })
}The public GET only returns published products. A hidden product gets 404, not 403, so the API does not reveal that it exists.
PATCH: partial update
// PATCH /api/products/:id
export async function PATCH(request: NextRequest, { params }: Context) {
// TODO(Part 10): await requireAdmin()
// Until then this endpoint is PUBLIC. Do not deploy it yet.
const { id } = await params
const result = await readJsonBody(request)
if (!result.ok) return result.response
const parsed = productPatchSchema.safeParse(result.body)
if (!parsed.success) {
return jsonError('Validasi gagal', 400, { fieldErrors: toFieldErrors(parsed.error) })
}
if (Object.keys(parsed.data).length === 0) {
return jsonError('Tidak ada field yang diubah', 400)
}
try {
const product = await prisma.product.update({
where: { id },
data: parsed.data,
select: productApiSelect,
})
revalidateTag('products', { expire: 0 })
return Response.json({ data: product })
} catch (error) {
const code = getPrismaErrorCode(error)
if (code === 'P2025') return jsonError('Produk tidak ditemukan', 404)
if (code === 'P2002') return jsonError('Slug sudah dipakai produk lain', 409)
console.error('PATCH /api/products/[id] failed', error)
return jsonError('Terjadi kesalahan pada server', 500)
}
}productSchema.partial() makes every field optional while keeping each field's rules. Sending {"price": -1} is still rejected. A PATCH with an empty {} body gets 400 because there is nothing to change. We use PATCH rather than PUT because the client only sends the fields that changed; by convention PUT replaces the whole resource.
DELETE
// DELETE /api/products/:id
export async function DELETE(_request: NextRequest, { params }: Context) {
// TODO(Part 10): await requireAdmin()
// Until then this endpoint is PUBLIC. Do not deploy it yet.
const { id } = await params
try {
await prisma.product.delete({ where: { id } })
} catch (error) {
const code = getPrismaErrorCode(error)
if (code === 'P2025') return jsonError('Produk tidak ditemukan', 404)
if (code === 'P2003') return jsonError('Produk sudah punya pesanan', 409)
console.error('DELETE /api/products/[id] failed', error)
return jsonError('Terjadi kesalahan pada server', 500)
}
revalidateTag('products', { expire: 0 })
return new Response(null, { status: 204 })
}204 No Content means success with no body. Note that we use new Response(null, ...) rather than Response.json, because a 204 response must not have a body.
The Status Codes We Use
| Code | Meaning | When |
|---|---|---|
| 200 OK | Success with data | Successful GET, PATCH |
| 201 Created | New resource created | Successful POST |
| 204 No Content | Success without a body | Successful DELETE |
| 400 Bad Request | Invalid input | Broken JSON, failed zod validation |
| 404 Not Found | Resource does not exist | Wrong ID or hidden product |
| 405 Method Not Allowed | Method not supported | Automatic from Next.js |
| 409 Conflict | Clashes with existing data | Duplicate slug, product still has orders |
| 415 Unsupported Media Type | Wrong body format | Not application/json |
| 500 Internal Server Error | Unexpected error | Details only in the server log |
In Part 10 we add 401 Unauthorized (not logged in) and 403 Forbidden (logged in, but not an admin).
Testing with curl
Run npm run dev and open a second terminal. On Windows, use Git Bash or WSL so the quotes and trailing \ work as shown. The IDs and data below are examples; yours will differ. Response messages are in Indonesian because they come from the same schema as the admin form.
List products
curl -s "http://localhost:3000/api/products?category=EBOOK&page=1"Result:
{
"data": [
{
"id": "cm3x9k2ab0002example",
"slug": "ebook-dasar-postgresql",
"title": "E-book Dasar PostgreSQL",
"price": 79000,
"category": "EBOOK",
"imageUrl": null
},
{
"id": "cm3x9k2ab0001example",
"slug": "ebook-belajar-nextjs",
"title": "E-book Belajar Next.js",
"price": 99000,
"category": "EBOOK",
"imageUrl": "/products/ebook-belajar-nextjs.jpg"
}
],
"meta": { "page": 1, "total": 2, "totalPages": 1 }
}Create a product
curl -i -X POST http://localhost:3000/api/products \
-H "Content-Type: application/json" \
-d '{"title":"Template Portfolio Developer","slug":"template-portfolio-developer","description":"Template portfolio responsif untuk developer, dibuat dengan Tailwind CSS.","price":89000,"category":"TEMPLATE"}'Result: (-i prints the headers)
HTTP/1.1 201 Created
location: /api/products/cm3xa1b2c0007example
content-type: application/json
{"data":{"id":"cm3xa1b2c0007example","slug":"template-portfolio-developer","title":"Template Portfolio Developer", ...}}Open http://localhost:3000/products in the browser. The new product shows up immediately, because the products-tagged cache has been expired.
Invalid input
curl -s -X POST http://localhost:3000/api/products \
-H "Content-Type: application/json" \
-d '{"title":"OK","slug":"Bukan Slug!","description":"pendek","price":-5,"category":"VIDEO"}'Result: status 400 with exactly the same messages as the admin form in Part 8. One schema, two entry points.
{
"error": "Validasi gagal",
"fieldErrors": {
"title": ["Judul minimal 3 karakter"],
"slug": ["Slug hanya boleh huruf kecil, angka, dan tanda hubung"],
"description": ["Deskripsi minimal 20 karakter"],
"price": ["Harga tidak boleh negatif"],
"category": ["Pilih kategori yang valid"]
}
}Conflict, update, delete, and a wrong method
Replace the example ID with the ID from your POST response.
# Same slug again -> 409
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://localhost:3000/api/products \
-H "Content-Type: application/json" \
-d '{"title":"Template Portfolio Developer","slug":"template-portfolio-developer","description":"Template portfolio responsif untuk developer, dibuat dengan Tailwind CSS.","price":89000,"category":"TEMPLATE"}'
# Partial update -> 200
curl -s -X PATCH http://localhost:3000/api/products/cm3xa1b2c0007example \
-H "Content-Type: application/json" \
-d '{"price":65000}'
# Delete -> 204, then GET -> 404
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE http://localhost:3000/api/products/cm3xa1b2c0007example
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/api/products/cm3xa1b2c0007example
# Unsupported method -> 405
curl -s -o /dev/null -w "%{http_code}\n" -X PUT http://localhost:3000/api/productsResult:
409
{"data":{"id":"cm3xa1b2c0007example","slug":"template-portfolio-developer","title":"Template Portfolio Developer","price":65000, ...}}
204
404
405Route Handler or Server Action?
| Need | Choice | Why |
|---|---|---|
| Forms and buttons in your own Next.js app | Server Action | One round trip, integrated with revalidation and useActionState, works without JavaScript |
| Mobile apps, scripts, or other services | Route Handler | Stable URLs and a JSON contract callable from any language |
| Third-party webhooks (for example payments) | Route Handler | The third party sends a plain HTTP request to a fixed URL |
| Reading data for your own pages | Server Component | Call Prisma directly as in Part 7; no need to fetch your own API |
| Non-HTML responses (CSV, files, RSS) | Route Handler | You fully control headers and body |
A common anti-pattern: a Server Component that calls fetch('/api/products') on its own API. That adds an unnecessary HTTP hop. Just call the function in lib/products.ts directly.
Common Mistakes
- Forgetting
await params. In Next.js 16paramsis a Promise, Route Handlers included. - Calling
await request.json()withouttry/catch. A malformed body makes the handler throw and the client gets a 500 when it should get a 400. - Using
Response.json(null, { status: 204 }). A 204 must not have a body. Usenew Response(null, { status: 204 }). - Returning whole Prisma objects or raw
error.message. Use an explicitselect, and log error details only on the server. - Writing separate validation for the API and the form. Sooner or later the rules drift apart. Reuse
productSchema. - Thinking the API is safe because the UI does not link to it. Every endpoint can be discovered and called by anyone. Authorization arrives in Part 10; do not deploy before then.
Exercises
- Allow PATCH to remove an image with
{"imageUrl": null}. Adjust the PATCH schema with.extend()and.nullable(), then test it with curl. - Reject bodies larger than 10 KB: check the
content-lengthheader inreadJsonBodyand return 413 Payload Too Large. - Add a
GET /api/products/slug/[slug]endpoint that reusesgetProductBySlugfrom Part 7, with a 404 when nothing is found.
Summary
- A Route Handler is a
route.tsthat exports one function per HTTP method and returns aResponse.paramsin dynamic routes is a Promise. GET /api/productsreusesparseProductQueryandgetProductsfrom Part 7, including query validation and caching.- POST and PATCH validate the body with
productSchema(and.partial()) from Part 8, answering with the right 400, 409, 415, or 201/200. - In Route Handlers, cache invalidation uses
revalidateTag('products', ...)becauseupdateTagis for Server Actions only. - Use Server Actions for forms in your own app, and Route Handlers for external clients, webhooks, and non-HTML responses.
DigiStore now has an admin UI and a REST API, but both are open to anyone. In Part 10 we add register, login, and logout with a cookie-based session, proxy.ts, and requireAdmin() in every Server Action and Route Handler that changes data, then build the "Beli" (buy) button and an orders page.
Related articles
PostgreSQL Zero to Advanced #8: Indexes & Performance
Read query plans with EXPLAIN ANALYZE and speed up a 500,000-row table with B-tree, composite, partial and GIN indexes.
PHP Zero to Advanced #8: Composer, Namespaces, PSR-4 Autoloading & Exceptions
Structure real PHP projects: organize code with namespaces, manage dependencies with Composer, autoload classes with PSR-4, and handle errors cleanly with exceptions.
Ruby on Rails Zero to Advanced #8: Forms, Strong Parameters & Full CRUD
Build a complete CRUD feature by hand with form_with and strong parameters, then compare it with what rails generate scaffold gives you for free.