Next.js Developer interview question · Most asked

What are Route Handlers and when should you use them instead of Server Actions?

Summary

Route Handlers (app/api/.../route.ts) export functions named after HTTP methods (GET, POST, ...) using Web Request/Response APIs. Use them for public REST endpoints, webhooks, third-party callbacks, file downloads and mobile clients; use Server Actions for mutations triggered from your own UI.

Longer Answer

Route Handlers support streaming responses, NextResponse.json(), cookies and headers, and can run on Node or Edge runtimes. In Next.js 15+, GET handlers aren't cached by default (export const dynamic = 'force-static' opts in).

Code Example

// app/api/webhooks/stripe/route.ts
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const body = await req.text();
  const sig = req.headers.get("stripe-signature")!;
  const event = stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!);
  await handleEvent(event);
  return NextResponse.json({ received: true });
}

Key Points

  • Export GET, POST, etc. from route.ts
  • Web Request/Response APIs
  • Webhooks, public APIs, mobile clients
  • Server Actions for UI mutations

More most-asked Next.js Developer questions

← All Next.js Developer questions