跳到內容

notFound

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

notFound()

呼叫 notFound() 函式會丟擲一個 NEXT_HTTP_ERROR_FALLBACK;404 錯誤,並終止其所在的路由段的渲染。指定一個 not-found 檔案 允許你透過在段內渲染“未找到”UI 來優雅地處理此類錯誤。

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 { id } = await params
  const user = await fetchUser(id)
 
  if (!user) {
    notFound()
  }
 
  // ...
}

須知notFound() 不需要你使用 return notFound(),因為它使用了 TypeScript never 型別。

版本歷史

版本更改
v13.0.0notFound 已引入。