はじめに
今回なぜNext.jsのApp Routerについて記事にしたかというとver.12まではPage Routerが主流でしてたがver.13以降はApp Routerがデフォルトのルーティング機能であるため簡単に使用方法をまとめてみました
App Routerとは
App Routerはディレクトリ構造に基づいたルーティング機能であり、以下のような特徴がある
- ファイルベースのルーティングでありディレクトリ構造そのものがルートである
- サーバーコンポーネントでありデフォルトはサーバー側でレンダリングされる
- ページごとにことなるレイアウトを簡単に適応できる
ディレクトリ構造
app/
├── layout.jsx // アプリ全体のレイアウト
├── page.jsx // ルートページ (/)
├── about/
│ ├── page.jsx // /about ページ
│ ├── layout.jsx // /about専用レイアウト
├── blog/
│ ├── [slug]/
│ │ ├── page.jsx // 動的ルート: /blog/:slug
│ ├── page.jsx // /blog ページ
├── globals.css
静的ルートの作成
各ディレクトリのpage.jsxをページに対応させる
URL
- app/page.jsx → /
- app/about/page.jsx → /about
export default function HomePage() {
return (
<main>
<h1>Welcome to the Home Page</h1>
</main>
);
}
レイアウトの設定
layout.jsxを使用してページ間で共有される要素を設定できる
- childrenは各ページのコンテンツが挿入される場所である
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
<main>{children}</main>
<footer>© 2025 My App</footer>
</body>
</html>
);
}
動的ルートの作成
動的ルートは[param]を使って設定する
- params.slugにはURLの値が渡される
- 例:/blog/post
export default function BlogPost({ params }) {
return (
<main>
<h1>Blog Post: {params.slug}</h1>
</main>
);
}
データフェッチの方法
サーバーコンポーネントを活用してデータを取得する
async function fetchPosts() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
return res.json();
}
export default async function Blog() {
const posts = await fetchPosts();
return (
<main>
<h1>Blog Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</main>
);
}
クライアントコンポーネントの利用
クライアントサイドで動作するコンポーネントを作成するにはファイルの先頭に"use client"
を追加する
App Routerでは、デフォルトがサーバーコンポーネントのため明示的にクライアントで指定する必要がある
"use client";
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
ネストしたレイアウト
特定のページやグループに専用のレイアウトを追加することが可能
/about以下のページでこのレイアウトが適用
export default function AboutLayout({ children }) {
return (
<section>
<h1>About Section</h1>
{children}
</section>
);
}
まとめ
App Routerの簡単な使用方法について学習しました。App Routerの大枠な部分を理解しuse Router
、use params
などのフックスを利用したルーティング方法やAPI通信を実現したいと思います