What are Next.js API routes?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Next.js basics — a prerequisite for any developer role.
Answer
Next.js API routes allow you to create backend API endpoints within the same Next.js project, without a separate server. App Router — Route Handlers: create a route.ts file in the app/ directory: // app/api/users/route.ts import { NextRequest, NextResponse } from "next/server"; export async function GET(request: NextRequest) { const users = await db.getUsers(); return NextResponse.json(users); } export async function POST(request: NextRequest) { const body = await request.json(); const user = await db.createUser(body); return NextResponse.json(user, { status: 201 }); }. Each HTTP method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) is exported as a named function. Pages Router API routes: // pages/api/users.ts export default function handler(req, res) { if (req.method === "GET") { res.json(users); } else if (req.method === "POST") { const user = createUser(req.body); res.status(201).json(user); } }. Route Handler features: access request via NextRequest (URL, headers, cookies, body); dynamic routes: app/api/users/[id]/route.ts; Edge runtime option for low-latency: export const runtime = "edge";; streaming responses; CORS handling; cookie management via cookies(). When to use: third-party API integrations, database operations (keep credentials server-side), webhooks from external services, form handling. For simple data needs, Server Actions or direct Server Component fetching is often cleaner.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Next.js codebase.
Previous
What is Incremental Static Regeneration (ISR) in Next.js?
Next
What are Server Actions in Next.js?