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

  • req is a Node.js IncomingMessage extended with req.query, req.cookies and a parsed req.body.
  • res is a ServerResponse with helpers: res.status(200), res.json(data), res.send(), res.redirect(), res.setHeader(), and res.revalidate(path) for on-demand ISR.
  • Dynamic routes work the same way as pages: pages/api/users/[id].ts gives req.query.id.

Config per route

Export config to change behavior:

  • api.bodyParser: false to handle the raw stream (webhooks with signature checks, file uploads).
  • api.bodyParser.sizeLimit: '2mb' to raise the default 1MB limit.
  • api.responseLimit to warn about large responses.
  • maxDuration on supported hosts.

Good practice

  • Check req.method and return 405 for unsupported methods.
  • Validate input and return useful status codes.
  • Do not call your own API routes from getServerSideProps or getStaticProps; 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].ts
2import type { NextApiRequest, NextApiResponse } from "next";
3import { db } from "@/lib/db";
4
5type User = { id: string; name: string };
6type Error = { error: string };
7
8export default async function handler(req: NextApiRequest, res: NextApiResponse<User | Error>) {
9 const { id } = req.query;
10
11 if (req.method !== "GET") {
12 res.setHeader("Allow", "GET");
13 return res.status(405).json({ error: "Method not allowed" });
14 }
15
16 const user = await db.user.findUnique({ where: { id: String(id) } });
17 if (!user) return res.status(404).json({ error: "Not found" });
18
19 res.setHeader("Cache-Control", "s-maxage=60, stale-while-revalidate=300");
20 return res.status(200).json({ id: user.id, name: user.name });
21}
22
23// 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.

Open in study app