【Next.js】not-found (404)
在 Next.js 中,not-found
頁面是用來顯示 404 頁面(找不到頁面)用的。從 Next.js 13(App Router)開始,你可以更靈活地自訂與觸發 not-found。
🧭 not-found
頁面用途
功能 | 說明 |
---|---|
預設 404 頁面 | 訪問不存在的路由時自動顯示 |
自訂 not-found | 你可以定義自訂的樣式與內容 |
手動觸發 404 | 在伺服器邏輯中,條件不符時主動觸發 notFound() |
📁 App Router (app/
目錄) 中的使用方式
📌 1. 建立 not-found.tsx
頁面
放在你想處理的路由資料夾中,例如:
app/
├── blog/
│ ├── [slug]/
│ │ ├── page.tsx
│ │ └── not-found.tsx 👈 對應 `/blog/[slug]` 找不到時
📦 app/blog/[slug]/not-found.tsx
export default function NotFound() {
return (
<div>
<h2>這篇文章不存在</h2>
<a href="/">回首頁</a>
</div>
);
}
📌 2. 在 page.tsx
中觸發 notFound()
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
範例
export default function GlobalNotFound() {
return (
<div style={{ textAlign: 'center', padding: '2rem' }}>
<h1>404 - 頁面找不到</h1>
<p>您訪問的頁面可能已被移除或從未存在。</p>
<a href="/">回首頁</a>
</div>
);
}
🧪 測試方式
測試路徑 | 預期結果 |
---|---|
/blog/xxx |
若 xxx 不存在 → 觸發 notFound() |
/some/random/page |
找不到任何匹配路由 → global 404 |
✅ 小結
功能 | 用法 |
---|---|
定義 not-found 頁面 | 在 app/***/not-found.tsx 中建立 |
全域 fallback 頁面 | 在 app/not-found.tsx |
手動觸發 404 | 使用 notFound() 函式 |