>_
EngineeringNotes
Back to Next.js Mastery

Backend APIs

Architecting high-performance Route Handlers and backend logic in the App Router.

1. Big Picture

Next.js is a Fullstack Framework. Beyond rendering UI, it allows you to build custom HTTP endpoints using Route Handlers. These replace the legacy api/ routes from the Pages Router with a more robust, standard-compliant architecture.

When to use Route Handlers?

External Access

When you need to provide an API for mobile apps, webhooks, or third-party services.

Legacy Integration

Handling complex HTTP methods (PUT, DELETE) or streaming non-HTML data.

2. Route Handlers (route.ts)

Route Handlers are defined in route.ts files inside the app directory. They give you full control over the Request and Response objects.

Standard GET Handler

app/api/users/route.js
javascript
import { NextResponse } from 'next/server';

export async function GET() {
  const data = await fetchExternalData();
  
  return NextResponse.json(
    { items: data }, 
    { status: 200 }
  );
}

Handling POST Data

app/api/contact/route.js
javascript
export async function POST(request) {
  const body = await request.json();
  const { email, message } = body;

  // Process data...
  return NextResponse.json({ success: true });
}

3. Dynamic Routes & Caching

The Caching Rule

GET requests are cached by default unless they use dynamic functions like cookies() or headers().

Dynamic GET Handler
javascript
import { cookies } from 'next/headers';

export async function GET(request) {
  const cookieStore = await cookies();
  const token = cookieStore.get('token');

  // This route is now dynamic and NOT cached
  return NextResponse.json({ authenticated: !!token });
}

4. Handlers vs. Server Actions

Server Actions are usually preferred for internal form submissions and database mutations. Route Handlers are for public or third-party API access.

Recommendation

"Use Route Handlers for resources. Use Server Actions for operations."

FeatureRoute HandlersServer Actions
Standard HTTPFull ControlRestricted
External CallYes (REST)Internal only
CORS SupportEasyDifficult
UsageThird-party APIsForms / Mutations

Advanced Interview Questions

Route Handlers turn Next.js into a powerful distributed backend for modern digital products.

Mastery Complete