notFound

notFound 函式允許您在路由區段內渲染 not-found 檔案,並自動注入 <meta name="robots" content="noindex" /> 標籤。

notFound()

呼叫 notFound() 函式會拋出 NEXT_NOT_FOUND 錯誤,並終止所在路由區段的渲染。透過設定 not-found 檔案,您可以在該區段內優雅地處理此類錯誤,並顯示「找不到頁面」的使用者介面。

app/user/[id]/page.js
import { notFound } from 'next/navigation'

async function fetchUser(id) {
  const res = await fetch('https://...')
  if (!res.ok) return undefined
  return res.json()
}

export default async function Profile({ params }) {
  const user = await fetchUser(params.id)

  if (!user) {
    notFound()
  }

  // ...
}

小知識:由於使用了 TypeScript 的 never 型別,notFound() 不需要使用 return notFound() 語法。

版本歷史

版本變更內容
v13.0.0新增 notFound 功能。

On this page