πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

API Routes

Next.js Backend🟒 Free Lesson

Advertisement

API Routes

Route handlers, middleware, request/response handling, and API design.

Overview

Next.js enables full-stack development with API routes in the App Router.

Key Concepts

  • Route Handlers β€” route.js files for API endpoints
  • HTTP Methods β€” GET, POST, PUT, DELETE handlers
  • Middleware β€” Request/response interception
  • Request/Response β€” Web API request and response objects
  • Streaming Responses β€” Send data progressively

Code Examples

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

export async function GET(request) {
  const users = await db.users.findMany();
  return NextResponse.json(users);
}

export async function POST(request) {
  const body = await request.json();
  const user = await db.users.create({ data: body });
  return NextResponse.json(user, { status: 201 });
}

// app/api/users/[id]/route.js
export async function GET(request, { params }) {
  const user = await db.users.findUnique({ where: { id: params.id } });
  if (!user) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }
  return NextResponse.json(user);
}

// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('token');
  
  if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  
  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*']
};

Practice

Build a REST API with CRUD operations and authentication middleware.

⭐

Premium Content

API Routes

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement