JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
Prev

Learn the concept

Route Handlers & API Routes

nextjs
mid
api

How do API routes work in Next.js?

nextjs
api-routes
route-handlers
backend
rest-api
http
Quick Answer

API routes let you build backend endpoints within your Next.js app. In the Pages Router, files in `pages/api/` export handlers. In the App Router, you create `route.ts` files that export functions named after HTTP methods (GET, POST, etc.).

Detailed Explanation

Pages Router API Routes:

  • Location: pages/api/
  • Export default handler function
  • Receives req and res objects (like Express)

App Router Route Handlers:

  • Location: app/api/.../route.ts
  • Export named functions: GET, POST, PUT, DELETE, etc.
  • Use Web Standard Request/Response objects
  • Can be static or dynamic

Common Use Cases:

  • Form submissions
  • Database operations
  • Third-party API proxying
  • Authentication
  • Webhooks
  • BFF (Backend for Frontend) pattern

Key Points:

  • Run only on server (never exposed to client)
  • Same domain, no CORS issues
  • Can access environment variables securely
  • Support middleware

Current Behavior in App Router:

  • headers() and cookies() are now async and must be awaited
  • Route handlers can return standard Response objects directly

Code Examples

App Router - Route HandlersTypeScript
// app/api/posts/route.ts
import { NextResponse } from 'next/server';

// GET /api/posts
export async function GET() {
  const posts = await db.posts.findMany();
  return NextResponse.json(posts);
}

// POST /api/posts
export async function POST(request: Request) {
  const body = await request.json();
  
  const post = await db.posts.create({
    data: {
      title: body.title,
      content: body.content,
    },
  });
  
  return NextResponse.json(post, { status: 201 });
}

// app/api/posts/[id]/route.ts
// GET /api/posts/123
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  const { id } = await params;
  const post = await db.posts.findUnique({
    where: { id },
  });
  
  if (!post) {
    return NextResponse.json(
      { error: 'Post not found' },
      { status: 404 }
    );
  }
  
  return NextResponse.json(post);
}

Real-World Applications

Use Cases

BFF Pattern

Using Route Handlers as a Backend-for-Frontend layer to aggregate and transform data from multiple microservices

Webhook Receiver

Creating POST route handlers to receive webhooks from Stripe, GitHub, or other services with secret validation

Server-Sent Events

Using streaming responses in route handlers for real-time updates like progress bars or live notifications

Mini Projects

REST API with Route Handlers

beginner

Build a complete CRUD API for a resource using App Router route handlers with validation and error handling

Real-Time SSE Chat

intermediate

Create a chat application using Route Handler streaming for Server-Sent Events with client-side EventSource

Industry Examples

Clerk

Uses Next.js route handlers for authentication webhooks and session management endpoints

Stripe

Provides Next.js route handler examples for payment intent creation and webhook handling

Resources

Route Handlers

docs

API Routes (Pages Router)

docs

Related Questions

What are Server Actions in Next.js and how do they handle form submissions and mutations?

senior
server-actions

How does Middleware work in Next.js and what are common use cases?

senior
middleware
Previous
How do you create dynamic routes with static generation in Next.js?
Prev