API-Route-Handler erstellen
Erstellen Sie robuste RESTful-API-Endpunkte mit den Route Handlers des App Routers für die Backend-Logik.
API-Route-Handler erstellen ist eine kostenlose Next.js 15 Fullstack Web Apps-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Next.js 15 Fullstack Web Apps-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Welcome to Route Handlers
In Next.js 15, Route Handlers are the powerful way to build backend API endpoints directly within your App Router project.
They allow you to create RESTful APIs, handle webhooks, or perform any server-side logic, all co-located with your frontend code.
Why Use Route Handlers?
Route Handlers offer several benefits:
- Simplicity: No need for a separate backend server.
- Co-location: API logic lives next to related UI components.
- Performance: Built on Web Standard APIs, making them efficient.
- Flexibility: Support all HTTP methods (GET, POST, PUT, DELETE, etc.).
Creating Your First Handler
To create a Route Handler, define a route.ts (or .js) file inside an app directory segment. For example, app/api/hello/route.ts will handle requests to /api/hello.
Inside this file, you export functions that match HTTP methods, like GET, POST, etc.
Handling GET Requests
The GET function handles HTTP GET requests. It receives a NextRequest object and should return a NextResponse.
Let's create a simple 'hello world' API endpoint.
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ message: 'Hello from API!' });
}How to Access GET Handler
The previous code snippet, placed in app/api/hello/route.ts, creates an endpoint accessible at /api/hello.
When you navigate to http://localhost:3000/api/hello in your browser, you'll see the JSON response: {"message":"Hello from API!"}.
Handling POST Requests
For data submission, you'll use the POST function. It also receives the NextRequest object, which contains the request body.
You can parse the JSON body using await request.json().
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
const data = await request.json();
return NextResponse.json(
{ message: 'Data received', data },
{ status: 200 }
);
}Accessing Request Details
The NextRequest object provides rich access to request details:
request.url: The full request URL.request.headers: Request headers (e.g.,request.headers.get('Content-Type')).request.nextUrl.searchParams: Query parameters (e.g.,?name=Alice).
These are crucial for dynamic and secure API logic.
Dynamic Segments in Handlers
Just like pages, Route Handlers can have dynamic segments. For example, app/api/items/[id]/route.ts.
You can access these dynamic parameters from the params object passed to your handler function.
import { NextRequest, NextResponse } from 'next/server';
interface Params {
params: { id: string };
}
export async function GET(
request: NextRequest,
{ params }: Params
) {
const id = params.id; // '123' for /api/items/123
return NextResponse.json({ itemId: id, message: 'Fetched item' });
}Setting Status and Headers
When returning a NextResponse, you can customize the HTTP status code and headers.
This is important for proper API communication, like indicating success (200, 201) or errors (400, 404, 500).
import { NextResponse } from 'next/server';
export async function DELETE() {
return new NextResponse(null, { status: 204 }); // No Content
}Quick Check: Handler Basics
You want to create an API endpoint at /api/products that returns a list of products when a GET request is made.
Which code snippet correctly sets up this handler in app/api/products/route.ts?
Recap: Building API Handlers
You've learned the fundamentals of Next.js 15 Route Handlers!
- They allow backend logic co-located in the
appdirectory. - Define handlers by exporting functions (
GET,POST, etc.) in aroute.tsfile. - Use
NextRequestto access request details andNextResponseto send responses. - Dynamic segments enable flexible API routes.
This powerful feature streamlines fullstack development in Next.js.
Häufig gestellte Fragen
Ist die Lektion „API-Route-Handler erstellen“ kostenlos?
Ja — der vollständige Text von „API-Route-Handler erstellen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Next.js 15 Fullstack Web Apps-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Next.js 15 Fullstack Web Apps-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „API-Route-Handler erstellen“?
Erstellen Sie robuste RESTful-API-Endpunkte mit den Route Handlers des App Routers für die Backend-Logik. Du übst Next.js 15 Fullstack Web Apps mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Next.js 15 Fullstack Web Apps zu starten?
Keine Vorkenntnisse erforderlich. Next.js 15 Fullstack Web Apps auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „API-Route-Handler erstellen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Next.js 15 Fullstack Web Apps-Lektion Code schreiben und ausführen?
Ja. Jede Next.js 15 Fullstack Web Apps-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- API-Route-Handler erstellen
- Anfragevalidierung und Sicherheit
- Externe Dienste integrieren
- Ratenbegrenzung und API-Fehlerbehandlung