Next.js App Routerの完全ガイド:基礎から実践まで
3分で読む
Tech Blog Admin

広告スペース
Slot: article-top
Format: horizontal
本番環境でGoogle AdSenseが表示されます
はじめに
Next.js 13から導入されたApp Routerは、React Server Components(RSC)をベースとした新しいルーティングシステムです。従来のPages Routerと比較して、より柔軟で強力な機能を提供します。
App Routerの主な特徴
1. ファイルベースルーティング
App Routerでは、app
ディレクトリ内のフォルダ構造がそのままURLのパスになります。
app/
├── page.tsx // /
├── about/
│ └── page.tsx // /about
└── blog/
├── page.tsx // /blog
└── [slug]/
└── page.tsx // /blog/[slug]
2. Server Components by Default
デフォルトですべてのコンポーネントがServer Componentとして動作します。これにより、以下のメリットがあります:
- バンドルサイズの削減: クライアントに送信されるJavaScriptが減少
- データフェッチの最適化: サーバー側で直接データベースにアクセス可能
- SEOの向上: サーバーサイドレンダリングによる検索エンジン最適化
3. レイアウトシステム
// app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="ja">
<body>
<Header />
<main>{children}</main>
<Footer />
</body>
</html>
)
}
実践的な使用例
データフェッチング
// app/posts/page.tsx
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 3600 } // 1時間ごとに再検証
})
return res.json()
}
export default async function PostsPage() {
const posts = await getPosts()
return (
<div>
{posts.map((post: Post) => (
<PostCard key={post.id} post={post} />
))}
</div>
)
}
Loading UIとError Handling
// app/posts/loading.tsx
export default function Loading() {
return <PostsSkeleton />
}
// app/posts/error.tsx
'use client'
export default function Error({
error,
reset,
}: {
error: Error
reset: () => void
}) {
return (
<div>
<h2>エラーが発生しました</h2>
<button onClick={() => reset()}>再試行</button>
</div>
)
}
パフォーマンス最適化のテクニック
1. 部分的な事前レンダリング
export const dynamic = 'force-static'
export const revalidate = 3600
2. Parallel Routes
複数のコンテンツを並列で表示:
app/
├── @team/
│ └── page.tsx
├── @analytics/
│ └── page.tsx
└── layout.tsx
3. Intercepting Routes
モーダルなどの実装に便利:
app/
├── feed/
│ └── page.tsx
└── (..)photo/[id]/
└── page.tsx
まとめ
App Routerは、Next.jsアプリケーションの開発をより効率的かつ強力にする革新的な機能です。Server Componentsとの組み合わせにより、パフォーマンスとDXの両方が大幅に向上します。
ぜひ、次のプロジェクトでApp Routerを活用してみてください!
広告スペース
Slot: article-bottom
Format: rectangle
本番環境でGoogle AdSenseが表示されます