0Pricing
Next.js 15 Fullstack Web Apps · レッスン

APIルートハンドラーの構築

App RouterのRoute Handlersを使って堅牢なRESTful APIエンドポイントを作成し、バックエンドロジックを実装します。

「APIルートハンドラーの構築」はCoddyKit上の無料Next.js 15 Fullstack Web Appsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これは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時間対応のAIチューター)、Next.js 15 Fullstack Web Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Next.js 15 Fullstack Web Appsコースには全4レッスンが含まれています。

「APIルートハンドラーの構築」で何を学びますか?

App RouterのRoute Handlersを使って堅牢なRESTful APIエンドポイントを作成し、バックエンドロジックを実装します。 ブラウザで直接実行するハンズオンコードでNext.js 15 Fullstack Web Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Next.js 15 Fullstack Web Appsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのNext.js 15 Fullstack Web Appsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン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に戻る