JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
Prev
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

Code Examples

App Router - Route Handlers
// 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 post = await db.posts.findUnique({
    where: { id: params.id },
  });
  
  if (!post) {
    return NextResponse.json(
      { error: 'Post not found' },
      { status: 404 }
    );
  }
  
  return NextResponse.json(post);
}

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?