not-found.js

not-found 檔案用於在路由區段中拋出 notFound 函數時渲染 UI。除了提供自訂 UI 外,Next.js 會針對串流回應返回 200 HTTP 狀態碼,非串流回應則返回 404

import Link from 'next/link'

export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  )
}

參考

Props

not-found.js 元件不接受任何 props。

須知事項:除了捕捉預期的 notFound() 錯誤外,根目錄的 app/not-found.js 檔案還會處理應用程式中所有未匹配的 URL。這表示當使用者造訪應用程式未處理的 URL 時,將會顯示由 app/not-found.js 檔案匯出的 UI。

範例

資料獲取

預設情況下,not-found 是一個伺服器元件 (Server Component)。您可以將其標記為 async 來獲取並顯示資料:

import Link from 'next/link'
import { headers } from 'next/headers'

export default async function NotFound() {
  const headersList = await headers()
  const domain = headersList.get('host')
  const data = await getSiteData(domain)
  return (
    <div>
      <h2>Not Found: {data.name}</h2>
      <p>Could not find requested resource</p>
      <p>
        View <Link href="/blog">all posts</Link>
      </p>
    </div>
  )
}

如果您需要使用像 usePathname 這樣的客戶端元件鉤子 (Client Component hooks) 來根據路徑顯示內容,則必須改在客戶端獲取資料。

版本歷史

版本變更內容
v13.3.0根目錄 app/not-found 開始處理全域未匹配的 URL。
v13.0.0not-found 功能首次引入。

On this page