nextjs runtime_error ai_generated true

Error: notFound() was called but the nearest error boundary is a client component. notFound() must be called within a server component or a server-side function.

ID: nextjs/not-found-in-client-component

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-08-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
14.2.0 active
15.0.0 active

Root Cause

The notFound() function from 'next/navigation' is invoked inside a Client Component or a context that lacks access to the server-side request handling pipeline, causing the error boundary to be a client-side component instead of the server-side not-found page.

generic

中文

从 'next/navigation' 调用的 notFound() 函数在客户端组件或缺乏服务器端请求处理管道的上下文中被调用,导致错误边界是客户端组件而非服务器端的 not-found 页面。

Official Documentation

https://nextjs.org/docs/app/api-reference/functions/not-found

Workarounds

  1. 95% success Move the notFound() call to a Server Component that wraps the Client Component. Pass a prop (e.g., notFound flag) from the server to the client.
    Move the notFound() call to a Server Component that wraps the Client Component. Pass a prop (e.g., notFound flag) from the server to the client.
  2. 80% success If you must trigger not-found from a Client Component, use a server action that returns a redirect to the not-found page, or use the error.js file pattern with notFound() in the parent layout.
    If you must trigger not-found from a Client Component, use a server action that returns a redirect to the not-found page, or use the error.js file pattern with notFound() in the parent layout.

中文步骤

  1. Move the notFound() call to a Server Component that wraps the Client Component. Pass a prop (e.g., notFound flag) from the server to the client.
  2. If you must trigger not-found from a Client Component, use a server action that returns a redirect to the not-found page, or use the error.js file pattern with notFound() in the parent layout.

Dead Ends

Common approaches that don't work:

  1. Wrapping the Client Component in a try-catch to catch notFound() 90% fail

    notFound() throws a special NEXT_NOT_FOUND error that cannot be caught by regular try-catch blocks. It must be handled by the Next.js routing layer.

  2. Importing notFound from 'next/client' (which doesn't exist) 100% fail

    There is no 'next/client' module. The function only exists in 'next/navigation' and its behavior is server-side only.

  3. Using notFound() inside a useEffect 95% fail

    notFound() is meant for synchronous server-side execution. Calling it asynchronously in useEffect doesn't trigger the server-side not-found page.