1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NEXT.JSにおける、API Routesと RSC(React Server Components)の違い

Last updated at Posted at 2025-01-26

NEXT.JSにおける、API Routesと RSC(React Server Components)の違いと、それぞれの実装について説明します。

1. API Routesについて

API Routes(app/api/###/route.ts )は、Next.js 13以降で導入された新しいフォルダ構造(App Router)を使用する場合に、APIルートを定義するファイルです。このファイルでは、サーバー側でHTTPリクエスト(GET, POST, PUT, DELETEなど)を処理し、データを返すエンドポイントを実装します。

特徴

  • サーバーサイド専用: クライアントから直接呼び出すのではなく、HTTPリクエストを介してデータや処理を提供します。
  • Middleware不要: エンドポイントごとに特定のロジックを定義できるため、単一のエンドポイントで処理を分けやすい。
  • Edge Functions対応: 必要に応じてエッジで実行するように設定できます。

実装例

次の例は、ユーザー情報を取得するシンプルなAPIエンドポイントです。

ディレクトリ構造:

app/api/users/route.ts

コード例:

import { NextResponse } from 'next/server';

// GETリクエストの処理
export async function GET(request: Request) {
  const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
  ];
  return NextResponse.json(users);
}

// POSTリクエストの処理
export async function POST(request: Request) {
  const body = await request.json();
  return NextResponse.json({
    message: 'User added',
    user: body,
  });
}

主な使用用途

  • クライアントとサーバー間のデータ通信。
  • CRUD処理(データベースの読み書き)。
  • サーバー側でのデータ処理(認証、外部APIのコールなど)。

2. RSC(React Server Components)について

RSCは、React 18以降で導入された機能で、Next.jsのApp Routerに統合されています。RSCは、サーバーサイドでReactコンポーネントをレンダリングし、その結果をクライアントに送信する仕組みです。

特徴

  • サーバーサイドでのレンダリング: データフェッチや処理をサーバー側で行い、HTMLとしてクライアントに送信します。
  • シームレスなクライアントとの統合: クライアントコンポーネント(Client Components)と組み合わせて使えます。
  • 効率的なパフォーマンス: 必要なデータだけをサーバーから送信するため、クライアント側の負担が軽減されます。

実装例

ディレクトリ構造:

app/users/page.tsx

コード例:

// サーバー側で実行されるReactコンポーネント
async function fetchUsers() {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  if (!res.ok) throw new Error('Failed to fetch users');
  return res.json();
}

export default async function UsersPage() {
  const users = await fetchUsers();

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map((user: any) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

主な使用用途

  • サーバーサイドでデータを直接取得してレンダリング。
  • SEOを重視するページや、初回表示速度が重要な場合。
  • データフェッチとUIロジックを簡素化。

3. 比較

項目 API Routes RSC(React Server Components)
役割 HTTPエンドポイントの実装 サーバー側でReactコンポーネントをレンダリング
動作環境 完全なサーバーサイド専用 サーバーサイドで動作しつつクライアントと統合
データ取得 クライアントがHTTPリクエストを送信しデータを取得 内部でデータフェッチを行いHTMLとして返す
使用例 API提供(RESTやGraphQLなど) ページやUIの構築
パフォーマンス 高速だがHTMLを返さない(JSONや他形式) 初期ロードが速い(HTMLを直接返す)

4. 併用する例

APIルートとRSCを組み合わせて使用する場合もあります。たとえば、APIルートでデータを提供し、それをRSC内で消費するケースです。

ディレクトリ構造:

app/api/users/route.ts
app/users/page.tsx

APIルート(app/api/users/route.ts

import { NextResponse } from 'next/server';

export async function GET() {
  const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
  ];
  return NextResponse.json(users);
}

RSC(app/users/page.tsx

export default async function UsersPage() {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/users`);
  const users = await res.json();

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map((user: any) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

結論

  • APIルートは、データ提供や外部との通信に特化。
  • RSCは、ページやUIを効率的にレンダリング。
  • 併用することで、柔軟かつ効率的なアプリケーション構築が可能です。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?