API Routes & Backend Handlers

One of the major reasons Next.js is considered a "Full-Stack" framework is its built-in API layer. You do not need a separate Express.js, Laravel, or Django backend; you can write backend code directly alongside your React frontend.

Route Handlers (App Router)

In the App Router (Next 13+), backend endpoints are created using Route Handlers. Instead of page.js, you create a file named route.js inside your app/api/ directories.

app/
└── api/
    └── users/
        └── route.js   --> API Endpoint: /api/users

Inside route.js, you export async functions matching HTTP Verbs (GET, POST, PUT, DELETE).

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

export async function GET(request) {
  // Access a database safely on the server here
  const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" }
  ];
  
  // Return a JSON response
  return NextResponse.json(users);
}

export async function POST(request) {
  // Read request body JSON
  const body = await request.json();
  
  // Insert into database logic here...

  return NextResponse.json({ message: "User created!" }, { status: 201 });
}

Pages Router API (`pages/api/`)

In the classical router, APIs were defined inside the pages/api/ directory. They exported a default handler taking req and res arguments, very similar to Express.js.

// pages/api/hello.js

export default function handler(req, res) {
  if (req.method === 'GET') {
    res.status(200).json({ name: 'John Doe' });
  } else {
    res.status(405).json({ message: 'Method Not Allowed' });
  }
}

Why use Next.js API Routes?

  • No CORS issues: Since the frontend and backend share the exact same domain, you never have to configure complex CORS headers.
  • Unified Deployment: Both frontend and backend are deployed together simultaneously as Serverless functions on platforms like Vercel.
  • Shared Code: You can reuse TypeScript interfaces, validation logic, and utility functions across both frontend and backend safely.

Edge Runtime

By default, API routes run in a Node.js environment. However, Next.js allows you to opt into the Edge Runtime. Edge functions run on Vercel's Edge Network (similar to Cloudflare Workers), ensuring milliseconds of latency globally.

export const runtime = 'edge'; // Opt into Edge Runtime

Conclusion

Next.js provides an incredibly robust backend architecture. For heavy, microservice-based enterprise architectures, you might still use a specialized backend. But for most applications, Next.js APIs are more than capable.