Next.js 15 App Router & Server Components

Ders 2/5 35 dakika

Route Handlers: Building APIs with Next.js

Create Route Handlers in app/api/, handle GET/POST/PUT/DELETE, return JSON responses, and protect endpoints.

What are Route Handlers?

Route Handlers are backend API endpoints defined in route.ts files. They can live inside app/api/ or anywhere in the app/ directory.

app/
└── api/
    ├── posts/
    │   ├── route.ts          → GET /api/posts
    │   └── [id]/
    │       └── route.ts      → GET/PUT/DELETE /api/posts/:id
    └── users/
        └── route.ts          → GET/POST /api/users

GET Endpoint

// app/api/posts/route.ts
import { NextRequest, NextResponse } from "next/server";

const posts = [
  { id: 1, title: "Next.js 15 is Awesome!", summary: "..." },
  { id: 2, title: "React Server Components", summary: "..." },
];

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const category = searchParams.get("category");

  const filtered = category
    ? posts.filter(p => p.category === category)
    : posts;

  return NextResponse.json(filtered);
}

POST Endpoint

export async function POST(request: NextRequest) {
  const body = await request.json();

  if (!body.title || !body.content) {
    return NextResponse.json(
      { error: "Title and content are required" },
      { status: 400 }
    );
  }

  const newPost = {
    id: Date.now(),
    ...body,
    createdAt: new Date().toISOString(),
  };

  return NextResponse.json(newPost, { status: 201 });
}

Dynamic Route Handler

// app/api/posts/[id]/route.ts
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params; // await required in Next.js 15!
  const post = posts.find(p => p.id === parseInt(id));

  if (!post) {
    return NextResponse.json({ error: "Post not found" }, { status: 404 });
  }

  return NextResponse.json(post);
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  // deletion logic...
  return new NextResponse(null, { status: 204 });
}

Önemli Noktalar

  • Route Handlers are route.ts files in app/api/
  • GET, POST, PUT, DELETE methods are supported
  • In Next.js 15, always await params in dynamic route handlers
  • NextResponse.json() returns JSON responses