Next.jsEasy
How do you create an API route in Next.js (Pages Router)?
Create a file under pages/api/, such as pages/api/hello.ts, and export a default function (req, res) => {}. It becomes the endpoint /api/hello, runs only on the server, and is never bundled for the browser.
The handler
reqis a Node.jsIncomingMessageextended withreq.query,req.cookiesand a parsedreq.body.resis aServerResponsewith helpers:res.status(200),res.json(data),res.send(),res.redirect(),res.setHeader(), andres.revalidate(path)for on-demand ISR.- Dynamic routes work the same way as pages:
pages/api/users/[id].tsgivesreq.query.id.
Config per route
Export config to change behavior:
api.bodyParser: falseto handle the raw stream (webhooks with signature checks, file uploads).api.bodyParser.sizeLimit: '2mb'to raise the default 1MB limit.api.responseLimitto warn about large responses.maxDurationon supported hosts.
Good practice
- Check
req.methodand return 405 for unsupported methods. - Validate input and return useful status codes.
- Do not call your own API routes from
getServerSidePropsorgetStaticProps; call the underlying function directly to avoid an extra network hop.
App Router equivalent
Route Handlers in app/api/.../route.ts use the Web Request/Response APIs and export one function per HTTP method. API routes in pages/api keep working in Next.js 16 and can coexist with the App Router.
Code example
tsx
1// pages/api/users/[id].ts2import type { NextApiRequest, NextApiResponse } from "next";3import { db } from "@/lib/db";45type User = { id: string; name: string };6type Error = { error: string };78export default async function handler(req: NextApiRequest, res: NextApiResponse<User | Error>) {9 const { id } = req.query;1011 if (req.method !== "GET") {12 res.setHeader("Allow", "GET");13 return res.status(405).json({ error: "Method not allowed" });14 }1516 const user = await db.user.findUnique({ where: { id: String(id) } });17 if (!user) return res.status(404).json({ error: "Not found" });1819 res.setHeader("Cache-Control", "s-maxage=60, stale-while-revalidate=300");20 return res.status(200).json({ id: user.id, name: user.name });21}2223// export const config = { api: { bodyParser: { sizeLimit: "2mb" } } };
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.