0
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ルーティング基礎

Last updated at Posted at 2025-10-23

Next.jsのルーティングは、ファイルとフォルダの構造がそのままWebサイトのURLになる「ファイルシステムベース」が基本です。

ただ、Next.jsには2種類のルーティング方式があり、どちらを使っているかでルールが少し異なります。

  • App Router (標準): app/ ディレクトリ
  • Pages Router (旧): pages/ ディレクトリ

ここでは、現在の標準であるApp Routerを中心に解説します。

App Router

App Routerのルールは「フォルダでURLパスを作り、page.tsxでUIを定義する」です。

フォルダがURLの「区切り(セグメント)」となり、その中にある page.tsx がそのページの本体(UIコンポーネント)となります。

フォルダ構成 URL
app/page.tsx / (トップ)
app/about/page.tsx /about
app/dashboard/settings/page.tsx /dashboard/settings

※フォルダを作っただけではページ公開されず、その中に page.tsx を置いて初めて、そのURLが有効になります。また、 appディレクトリ内に components を作成して各コンポーネントを配置するような設計でも、page.tsxdefault exportされていなければ、機能しないです。

pages と layouts

  • 各ルート固有UIのpages
app/
|-- page.tsx
|-- blog/
|   |-- page.tsx
|   |-- about/
|       |-- page.tsx
  • ページで共通のUIを作成するためにLayoutsを使用
app/
|-- page.tsx
|-- blog/
|   |-- page.tsx
|   |-- layout.tsx
|   |-- about/
|       |-- page.tsx
|       |-- layout.tsx

layout.tsxは、同じ階層や下層ページ(page.tsx)を自動的にラップします。

layout.tsxの働きを「額縁」に例えると、

  • layout.tsx (額縁): ヘッダー、フッター、サイドバーなど、複数のページで共通して表示したい部分

  • page.tsx (絵画): ページ固有のコンテンツ(記事、プロフィール、ダッシュボードなど)

  • children (絵を入れるスペース): layout.tsxは、childrenpropsとして受け取ります。このchildrenの部分に、page.tsx(絵画)や、さらに内側にあるlayout.tsx(内側の額縁)を自動的に挿入します(page.tsxの内容をchildrenとして表示することができる)

以下のイメージ

layout.tsx
import React from 'react';
import Link from 'next/link';

export default function BlogLayout({
  children, // ここに、blogのpage.tsxなどが入る
}: {
  children: React.ReactNode;
}) {
  return (
    // このレイアウト自体、app/layout.tsxのchildrenとして挿入される
    <div className="blog-container">
      
      {/* ヘッダー */}
      <header className="blog-header">
        <Link href="/blog">
          <h1>My Tech Blog</h1>
        </Link>
        <nav>
          <Link href="/">Home</Link>
          <Link href="/about">About</Link>
        </nav>
      </header>
      
        {/* 記事などメインコンテンツ */}
        <main className="blog-content">
          {children} 
        </main>
      </div>

    </div>
  );
}

その他、Template や動的ルートを作成することも勿論できるのですが後ほど

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