# 【Next.js】not-found (404)

在 Next.js 中，`not-found` 頁面是用來顯示 **404 頁面**（找不到頁面）用的。從 Next.js 13（App Router）開始，你可以更靈活地**自訂與觸發 not-found**。

---

## 🧭 `not-found` 頁面用途

<table id="bkmrk-%E5%8A%9F%E8%83%BD-%E8%AA%AA%E6%98%8E-%E9%A0%90%E8%A8%AD-404-%E9%A0%81%E9%9D%A2-%E8%A8%AA%E5%95%8F%E4%B8%8D%E5%AD%98"><thead><tr><th>功能</th><th>說明</th></tr></thead><tbody><tr><td>預設 404 頁面</td><td>訪問不存在的路由時自動顯示</td></tr><tr><td>自訂 not-found</td><td>你可以定義自訂的樣式與內容</td></tr><tr><td>手動觸發 404</td><td>在伺服器邏輯中，條件不符時主動觸發 `notFound()`</td></tr></tbody></table>

---

## 📁 App Router (`app/` 目錄) 中的使用方式

### 📌 1. 建立 `not-found.tsx` 頁面

放在你想處理的路由資料夾中，例如：

```
app/
├── blog/
│   ├── [slug]/
│   │   ├── page.tsx
│   │   └── not-found.tsx   👈 對應 `/blog/[slug]` 找不到時

```

### 📦 `app/blog/[slug]/not-found.tsx`

```tsx
export default function NotFound() {
  return (
    <div>
      <h2>這篇文章不存在</h2>
      <a href="/">回首頁</a>
    </div>
  );
}

```

---

### 📌 2. 在 `page.tsx` 中觸發 `notFound()`

```tsx
import { notFound } from 'next/navigation';

export default function BlogPost({ params }: { params: { slug: string } }) {
  const validSlugs = ['a', 'b', 'c'];

  if (!validSlugs.includes(params.slug)) {
    notFound(); // 👈 主動觸發 404 頁面
  }

  return <h1>Blog: {params.slug}</h1>;
}

```

---

## 📁 Global Not Found Page

如果你在 `app/not-found.tsx` 建立，這就是全站共用的 404 頁面。

```
app/
├── not-found.tsx        👈 對應任何未定義頁面

```

---

## 📦 `app/not-found.tsx` 範例

```tsx
export default function GlobalNotFound() {
  return (
    <div style={{ textAlign: 'center', padding: '2rem' }}>
      <h1>404 - 頁面找不到</h1>
      <p>您訪問的頁面可能已被移除或從未存在。</p>
      <a href="/">回首頁</a>
    </div>
  );
}

```

---

## 🧪 測試方式

<table id="bkmrk-%E6%B8%AC%E8%A9%A6%E8%B7%AF%E5%BE%91-%E9%A0%90%E6%9C%9F%E7%B5%90%E6%9E%9C-%2Fblog%2Fxxx-"><thead><tr><th>測試路徑</th><th>預期結果</th></tr></thead><tbody><tr><td>`/blog/xxx`</td><td>若 `xxx` 不存在 → 觸發 `notFound()`</td></tr><tr><td>`/some/random/page`</td><td>找不到任何匹配路由 → global 404</td></tr></tbody></table>

---

## ✅ 小結

<table id="bkmrk-%E5%8A%9F%E8%83%BD-%E7%94%A8%E6%B3%95-%E5%AE%9A%E7%BE%A9-not-found-%E9%A0%81"><thead><tr><th>功能</th><th>用法</th></tr></thead><tbody><tr><td>定義 not-found 頁面</td><td>在 `app/***/not-found.tsx` 中建立</td></tr><tr><td>全域 fallback 頁面</td><td>在 `app/not-found.tsx`</td></tr><tr><td>手動觸發 404</td><td>使用 `notFound()` 函式</td></tr></tbody></table>