【現場で役立つ】Next.js App Router入門ガイド
Next.js 13で登場した App Router
。
名前は聞いたことあるけど…
- 何が変わったの?
-
pages
との違いって? - 実務でどう使うの?
そんな疑問を抱えたあなたへ。
この記事では、実プロジェクトで迷わない App Router の使い方をわかりやすく解説します。
App Routerとは?
Next.js 13以降で導入された新しいルーティングの仕組みです。
以下のような特徴があります:
- ファイルベースルーティング(従来通り)
- サーバーコンポーネントが標準
- レイアウト(layout.tsx)が階層で定義できる
- loading.tsx / error.tsx などのUI管理が簡単
- APIルートも
app/
内で完結
Pages Routerとの違い
項目 | Pages Router (pages/ ) |
App Router (app/ ) |
---|---|---|
コンポーネント種別 | クライアントが基本 | サーバーが基本(use client で明示) |
レイアウト設計 |
_app.tsx / _document.tsx
|
階層ごとに layout.tsx が定義可 |
データ取得 |
getServerSideProps など |
直接 fetch() を使える |
ローディングUI | 自作する必要あり |
loading.tsx が使える |
エラー処理 |
ErrorBoundary 手動設定 |
error.tsx で自動 |
API定義 | pages/api/ |
app/api/ に route.ts を作る |
ディレクトリ構成例
app/
├── layout.tsx # ルートレイアウト(全ページ共通)
├── page.tsx # トップページ(/)
├── about/
│ └── page.tsx # /about ページ
├── dashboard/
│ ├── layout.tsx # /dashboard 配下の共通レイアウト
│ ├── loading.tsx # ローディングUI
│ ├── error.tsx # エラーUI
│ └── page.tsx # /dashboard ページ本体
├── api/
│ └── hello/
│ └── route.ts # APIエンドポイント /api/hello
レイアウトとページの基本
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="ja">
<body>
<header>Header</header>
<main>{children}</main>
<footer>Footer</footer>
</body>
</html>
);
}
// app/page.tsx
export default function Home() {
return <h1>トップページ</h1>;
}
サーバーコンポーネントとクライアントコンポーネント
サーバーコンポーネント(デフォルト)
// app/page.tsx
export default async function Page() {
const res = await fetch('https://api.example.com/data', { cache: 'no-store' });
const data = await res.json();
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
クライアントコンポーネント(明示が必要)
// app/components/Counter.tsx
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>カウント: {count}</button>;
}
loading.tsx / error.tsx
// app/dashboard/loading.tsx
export default function Loading() {
return <p>読み込み中...</p>;
}
// app/dashboard/error.tsx
'use client';
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
return (
<div>
<p>エラーが発生しました: {error.message}</p>
<button onClick={reset}>再試行</button>
</div>
);
}
APIも定義できる
// app/api/hello/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ message: 'Hello from App Router API!' });
}
参考リンク
- Next.js公式ドキュメント(App Router): https://nextjs.org/docs/app
- Next.js App Router チュートリアル: https://nextjs.org/learn