紀錄工作經驗、相關知識,解決技術相關問題。

Next

Next.js not-found.js 用法:notFound() 404 頁面、global-not-found.js 與狀態碼 200 的情況

Next.js not-found.js 用法:notFound() 404 頁面、global-not-found.js 與狀態碼 200 的情況 特色圖片

Next.js App Router 的 not-found.js(TypeScript 專案寫成 not-found.tsx)是「找不到資料」時顯示的畫面:在路由區段裡呼叫 notFound(),Next.js 會中止該區段的渲染,改顯示最近一層的 not-found.js,並加上 <meta name="robots" content="noindex" />。放在 app 根目錄的 not-found.js 還會接手整個網站對不到路由的網址。本文以 Next.js 16(範例在 16.4.3、開啟 cacheComponents 的專案執行)說明 not-found.js 寫法、notFound() 的呼叫位置、什麼情況回 404、什麼情況回 200,以及實驗性的 global-not-found.js。

not-found.js 基本寫法

not-found.js 預設匯出一個元件,不接受任何 props。放在哪個路由資料夾,就負責那一層與底下路由呼叫 notFound() 時的畫面:

// app/blog/[id]/not-found.tsx
import Link from 'next/link'

export default function NotFound() {
  return (
    <main>
      <h1>找不到這篇文章</h1>
      <p>文章可能已經刪除,或網址打錯了。</p>
      <Link href="/">回首頁</Link>
    </main>
  )
}

not-found.js 預設是 Server Component,可以寫成 async 函式抓資料(例如用 headers() 讀網域再查站台名稱)。要用 usePathname 這類 Client Component Hook 依路徑顯示內容時,官方說明要改在用戶端抓資料。

在元件階層裡,not-found.js 位在 loading.js 與 page.js 之間,外面包著同一層 loading.js 的 <Suspense> 與 error.js 的錯誤邊界。各特殊檔案的包覆順序可以參考 Next.js layout.js 用法。

在頁面呼叫 notFound()

notFound() 從 next/navigation 匯入,查不到資料時呼叫。下面的 getPost() 為了示範直接從陣列查文章,正式專案換成查資料庫或 API:

// app/lib/posts.ts
export type Post = { id: string; title: string; content: string }

const posts: Post[] = [
  { id: '1', title: 'Next.js 路由入門', content: 'App Router 用資料夾定義路由。' },
  { id: '2', title: 'not-found.js 用法', content: '找不到資料時呼叫 notFound()。' },
]

export async function getPost(id: string): Promise<Post | undefined> {
  'use cache'
  await new Promise((resolve) => setTimeout(resolve, 300))
  return posts.find((post) => post.id === id)
}
// app/blog/[id]/page.tsx
import { notFound } from 'next/navigation'
import { getPost } from '@/app/lib/posts'

export function generateStaticParams() {
  return [{ id: '1' }, { id: '2' }]
}

export default async function PostPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const post = await getPost(id)

  // 查無資料:中止渲染,改顯示最近一層的 not-found.tsx
  if (!post) {
    notFound()
  }

  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </article>
  )
}

notFound() 的作用是丟出一個 NEXT_HTTP_ERROR_FALLBACK;404 錯誤,所以不用寫 return notFound();它的 TypeScript 回傳型別是 never,if 之後 post 會自動收斂成有值的型別。開啟 /blog/42 這類查不到的網址,畫面換成 not-found.tsx:

Next.js 16.4.3 正式環境:開啟不存在的文章 id,畫面顯示 blog/[id]/not-found.tsx 的「找不到這篇文章」

getPost() 加 'use cache' 是因為範例專案開了 cacheComponents:有 generateStaticParams 時,next build 會用範例參數實際渲染頁面,資料函式沒有快取就會失敗,錯誤開頭是 Next.js encountered uncached or runtime data during prerendering.。沒開 cacheComponents 的專案不需要這行('use cache' 本身也要開了 cacheComponents 才能用)。generateStaticParams 與 params 的寫法可以參考 Next.js 動態路由用法。

找不到 not-found.js 時往上一層找

同一層沒有 not-found.js 時,Next.js 往上找最近一層的 not-found.js;整條路徑都沒有,就顯示內建的「404 | This page could not be found.」:

Next.js 16.4.3 正式環境:路徑上沒有 not-found.tsx 時,notFound() 顯示內建的 404 This page could not be found. 畫面

內建的 404 畫面依作業系統的 prefers-color-scheme 切換深淺色,不會讀 <html> 上的 class 或 data-theme。網站有自己的主題切換時,自訂一個 not-found.js 最直接。

另一個容易誤會的地方:只有根目錄的 app/not-found.js 會處理「對不到路由」的網址。上面的 blog/[id]/not-found.tsx 只在 notFound() 被呼叫時出現;使用者打 /blog/1/abc 這種不存在的路徑,顯示的是根層的 not-found.js(沒有就是內建 404),不是 blog/[id] 那一層。

根層 not-found.js 與 metadata

app/not-found.tsx 同時負責兩件事:根層以下沒有更近的 not-found.js 時接手 notFound(),以及整個網站對不到路由的網址。它會被根 layout 包住,所以網站的頁首、字型、全域樣式都會套用。根層的 not-found.js 可以匯出 metadata 或 generateMetadata 設定 404 頁的標題:

// app/not-found.tsx
import Link from 'next/link'
import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: '找不到頁面',
}

export default function NotFound() {
  return (
    <main>
      <h1>404:找不到頁面</h1>
      <p>網址可能打錯了,或頁面已經移除。</p>
      <Link href="/">回首頁</Link>
    </main>
  )
}

開啟 /nope-xyz 這種不存在的網址,回應 HTTP 404,<title> 是「找不到頁面」,HTML 帶 noindex。

404 還是 200:看呼叫時串流開始了沒

官方文件寫得很直接:串流開始前呼叫 notFound(),回應 404;串流開始後,狀態碼已經隨回應標頭送出,只能維持 200,Next.js 改在串流內容裡渲染 not-found.js,兩種情況都會加上 noindex。

串流什麼時候開始?Suspense 的 fallback(例如 loading.tsx)渲染,或 Server Component 在 <Suspense> 裡暫停時,回應主體就開始送出。官方建議把存在與否的檢查放在資料存取函式裡,用 <Suspense> 包住,讓頁面外殼先送出:

// app/news/[id]/page.tsx
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
import { getPost } from '@/app/lib/posts'

async function Article({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const post = await getPost(id)
  if (!post) {
    notFound()
  }
  return (
    <article>
      <h2>{post.title}</h2>
      <p>{post.content}</p>
    </article>
  )
}

export default function NewsPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  return (
    <main>
      <h1>部落格</h1>
      <Suspense fallback={<p>載入中…</p>}>
        <Article params={params} />
      </Suspense>
    </main>
  )
}

/news/999 每次都回 HTTP 200:送出的 HTML 先有「部落格」標題與「載入中…」,接著串流進來的 news/[id]/not-found.tsx 取代整個頁面區段,HTML 帶 noindex。

開啟 cacheComponents 時還有一個情況:前一節 blog/[id] 雖然在頁面最上層呼叫 notFound(),但 generateStaticParams 沒列到的 id(例如 /blog/999)會先送出預先產生的頁面外殼,第一次請求回 200(回應標頭帶 x-nextjs-postponed: 1),同一個網址之後的請求才回 404。官方文件對這類路由的說明是「以執行時參數渲染的頁面,在第一次成功請求後存到磁碟」。

狀態碼對 SEO、監控或稽核紀錄很重要時,檢查要在串流開始前完成。官方建議在 Proxy 檢查 slug,再 rewrite 到 not-found 路由或直接回 404,並提醒 Proxy 的檢查要快、不要在那裡抓完整內容(Next.js 16 起 middleware 檔案慣例已改名為 proxy)。

在 Route Handler 回 404

notFound() 可以在 Server Components、Server Functions(Server Action)與 Route Handlers 呼叫。在 Route Handler 裡呼叫,呼叫端收到 404:

// app/api/posts/[id]/route.ts
import { notFound } from 'next/navigation'
import { getPost } from '@/app/lib/posts'

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params
  const post = await getPost(id)
  if (!post) {
    notFound()
  }
  return Response.json(post)
}

/api/posts/1 回 200 與文章 JSON;/api/posts/999 回 404。

global-not-found.js:多個根 layout 時的全站 404

global-not-found.js 從 Next.js 15.4.0 開始提供,到 Next.js 16 文件仍標示為實驗性功能。它只處理「網址完全對不到任何路由」的情況,Next.js 會略過一般渲染、直接回傳這一頁。官方列出兩種適用情境:

  • 有多個根 layout(例如 app/(admin)/layout.tsx 與 app/(shop)/layout.tsx),沒有單一 layout 可以組出全站 404。
  • 根 layout 放在頂層動態區段裡(例如 app/[country]/layout.tsx),不容易組出一致的 404 頁。

先在 next.config.ts 開啟 experimental.globalNotFound,已有其他設定時加進同一個物件:

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    globalNotFound: true,
  },
}

export default nextConfig

再建立 app/global-not-found.tsx。因為不經過 layout,這個檔案必須自己回傳完整的 HTML 文件(含 <html> 與 <body>),全域樣式、字型也要自己匯入:

// app/global-not-found.tsx
import './globals.css'
import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: '404 - 找不到頁面',
  description: '你要找的頁面不存在。',
}

export default function GlobalNotFound() {
  return (
    <html lang="zh-Hant-TW">
      <body>
        <main>
          <h1>404:找不到頁面</h1>
          <p>網址沒有對應的頁面,請確認後再試一次。</p>
          <a href="/">回首頁</a>
        </main>
      </body>
    </html>
  )
}

開啟後執行 next build,輸出開頭會列出「Experiments (use with caution): ✓ globalNotFound」。/nope-xyz 回 HTTP 404,<title> 是「404 – 找不到頁面」,<html lang="zh-Hant-TW"> 來自這個檔案,HTML 同樣帶 noindex:

Next.js 16.4.3 正式環境:開啟 experimental.globalNotFound 後,不存在的網址顯示 global-not-found.tsx 的「404:找不到頁面」

要注意 global-not-found.js 不會接手 notFound():在沒有 not-found.js 的路由區段呼叫 notFound(),顯示的仍是根 layout 裡的內建「This page could not be found.」,<title> 也是根 layout 的設定。路由內的 404 畫面還是要靠各層的 not-found.js。

注意事項:try/catch 與沒有 await 的 Promise

try/catch 會吞掉 notFound()

notFound() 靠丟出錯誤運作,包在 try/catch 裡會被 catch 接走,不會顯示 not-found.js。下面的 loadTitle() 如果拿掉 unstable_rethrow(err),查不到的 id 會顯示「文章載入失敗」,伺服器記錄印出 Error: NEXT_HTTP_ERROR_FALLBACK;404。官方建議在 catch 區塊最上方呼叫 unstable_rethrow,把 Next.js 內部的中斷交回框架處理:

import { notFound, unstable_rethrow } from 'next/navigation'
import { getPost } from '@/app/lib/posts'

async function loadTitle(id: string) {
  try {
    const post = await getPost(id)
    if (!post) {
      notFound()
    }
    return post.title
  } catch (err) {
    unstable_rethrow(err) // 讓 notFound() 的中斷繼續往上丟
    console.error('loadTitle 失敗', err)
    return '文章載入失敗'
  }
}

加上之後,查不到的 id 正常顯示 404 畫面並帶 noindex。unstable_rethrow 名稱帶 unstable_,官方文件標示為不穩定 API。一般錯誤交給 error.js 處理,寫法可以參考 Next.js error.js 用法。

沒有 await 的 Promise 不會觸發 not-found.js

notFound() 必須在渲染路徑上執行:寫在元件裡,或寫在元件會 await 的函式裡。呼叫它的函式沒有被 await,錯誤丟在沒有人接的地方,畫面不會顯示 not-found.js,開發模式的伺服器記錄會出現 unhandledRejection: NEXT_HTTP_ERROR_FALLBACK;404。

權限不足用 forbidden()

notFound() 表示「資源不存在」。已登入但權限不足要回 403 時,改用 forbidden() 與 forbidden.js,設定方式見 Next.js forbidden.js 用法。

參考資料與延伸閱讀

發佈留言