Next.js API Routes Explained — Backend API in Next.js
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Next.js API Routes Explained. We cover key concepts, practical examples, and best practices to help you master this topic.
Next.js API routes let you build backend API endpoints within your Next.js application, handling HTTP requests with full access to request and response objects.
What You'll Learn
- Route handlers in App Router
- Pages Router API routes
- HTTP method handling
- Middleware for API validation
- Database and external API integration
Why It Matters
API routes eliminate the need for a separate backend server for simple APIs. They integrate seamlessly with Next.js authentication, middleware, and deployment.
// app/api/tasks/route.js — App Router route handler
import { NextResponse } from "next/server";
export async function GET(request) {
const { searchParams } = new URL(request.url);
const status = searchParams.get("status");
const tasks = await db.getTasks({ status });
return NextResponse.json(tasks);
}
export async function POST(request) {
const body = await request.json();
if (!body.title) {
return NextResponse.json({ error: "Title required" }, { status: 400 });
}
const task = await db.createTask(body);
return NextResponse.json(task, { status: 201 });
}
export async function DELETE(request) {
const { id } = await request.json();
await db.deleteTask(id);
return NextResponse.json({ success: true });
}
// middleware.js — API middleware
import { NextResponse } from "next/server";
export function middleware(request) {
if (request.nextUrl.pathname.startsWith("/api")) {
const token = request.cookies.get("session");
if (!token) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
}
return NextResponse.next();
}
Expected output: Full CRUD API at /api/tasks with validation, auth middleware, and proper HTTP status codes.
← Previous
Next.js ISR Explained — Incremental Static Regeneration
Next →
Next.js Middleware Explained — Request Interception
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro