2
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 AppRouter の Web API の実装機能のひとつである Route Handlers の概要を記載します。

開発環境

開発環境は以下の通りです。

  • Windows 11
  • Next.js 14.2.13
  • React 18.3.1
  • TypeScript 5.5.4

ファイルの設置

Route Handlers は、app ディレクトリ内に route.ts というファイル名で定義する必要があります。

例として app/api/hello/route.ts というテキストで "Hello World!" を返す Route Handler を定義します。

app/api/hello/route.ts
import { NextResponse } from "next/server";

export async function GET() {
  return new NextResponse("Hello World!");
}

この Route Handler をページコンポーネントで呼び出します。

app/page.tsx
export default async function Home() {
  const res = await fetch("http://localhost:3000/api/hello");
  const text = await res.text();

  return (
    <div>
      <h1>Message from Hello API</h1>
      <p>{text}</p>
    </div>
  );
}

画面上に Route Handler から受け取ったテキストが表示されます。

image.png

Route Handlers (route.ts) は、page.tsxlayout.tsx 同様 app ディレクトリ内にネストして設置することができます。ただ、page.tsx と同じ階層に置くことはできません。

Page Route 🙆‍♂️ / 🙅‍♂️
app/page.ts app/route.ts 🙅‍♂️
app/page.ts app/api/route.ts 🙆‍♂️
app/[user]/page.ts app/api/route.ts 🙆‍♂️

HTTP リクエストメソッドごとの定義

Route Handlers は HTTP リクエストメソッドである GETPOSTPUTPATCHDELETEHEADOPTIONS をサポートしています。
サポート対象外のメソッドがコールされた場合、405 Method Not Allowed を返します。

app/api/unsupported-method/route.ts
import { NextResponse } from "next/server";

export async function HOGE() {
  return new NextResponse("hoge");
}

image.png

NextRequest / NextReaponse

Route Handlers は Web 標準の Fetch API に準拠しています。

そのため、Next.js の NextRequestNextReaponse は、それぞれ Fetch API の RequestResponse を基に作られています。

以下のように HTTP Status コードの指定もできます。

route.ts
if (!authorized) {
  return new NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}

参照

2
0
0

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
2
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?