0Pricing
Next.js 15 Fullstack Web Apps · Урок

Создание обработчиков маршрутов API

Создавайте надёжные конечные точки RESTful API с помощью обработчиков маршрутов App Router для реализации серверной логики.

«Создание обработчиков маршрутов API» — бесплатный урок Next.js 15 Fullstack Web Apps на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack Web Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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 app directory.
  • Define handlers by exporting functions (GET, POST, etc.) in a route.ts file.
  • Use NextRequest to access request details and NextResponse to send responses.
  • Dynamic segments enable flexible API routes.

This powerful feature streamlines fullstack development in Next.js.

Часто задаваемые вопросы

Урок «Создание обработчиков маршрутов API» бесплатный?

Да — полный текст урока «Создание обработчиков маршрутов API» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack Web Apps, подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Чему я научусь в уроке «Создание обработчиков маршрутов API»?

Создавайте надёжные конечные точки RESTful API с помощью обработчиков маршрутов App Router для реализации серверной логики. Ты практикуешь Next.js 15 Fullstack Web Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack Web Apps?

Предыдущий опыт не требуется. Next.js 15 Fullstack Web Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Создание обработчиков маршрутов API»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack Web Apps?

Да. Каждый урок Next.js 15 Fullstack Web Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Создание обработчиков маршрутов API
  2. Проверка запросов и безопасность
  3. Интеграция внешних сервисов
  4. Ограничение частоты запросов и обработка ошибок API
← Назад к Next.js 15 Fullstack Web Apps