nextjs runtime_error ai_generated true

Error: Invariant: headers() expects to have requestAsyncStorage, but none is available.

ID: nextjs/invariant-requestAsyncStorage-not-available

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
1Evidence
2024-07-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
[email protected] active
[email protected] active
[email protected] active

Root Cause

The headers() function is called outside of a valid request context, such as in a synchronous function, a utility file, or a component that runs during build time without a request.

generic

中文

headers() 函数在有效的请求上下文之外被调用,例如在同步函数、实用程序文件或在没有请求的构建期间运行的组件中。

Official Documentation

https://nextjs.org/docs/messages/invariant-headers-requestAsyncStorage

Workarounds

  1. 90% success Move the headers() call into an async Server Component or API route where the request context is available.
    Move the headers() call into an async Server Component or API route where the request context is available.
  2. 85% success If you need headers in a utility function, pass them as a parameter from a Server Component.
    If you need headers in a utility function, pass them as a parameter from a Server Component.
  3. 80% success If the error occurs in a middleware, ensure headers() is called at the top level of the middleware function, not inside a nested callback or conditional.
    If the error occurs in a middleware, ensure headers() is called at the top level of the middleware function, not inside a nested callback or conditional.

中文步骤

  1. 将 headers() 调用移入可用的请求上下文的异步服务器组件或 API 路由中。
  2. 如果在实用程序函数中需要标头,请从服务器组件将它们作为参数传递。
  3. 如果错误发生在中间件中,请确保 headers() 在中间件函数的顶层调用,而不是在嵌套的回调或条件语句中。

Dead Ends

Common approaches that don't work:

  1. 90% fail

    headers() is a server-only function; it cannot be called in client components even in useEffect.

  2. 85% fail

    The function will still throw an invariant error, and the catch block will not provide valid header data.

  3. 80% fail

    These functions run at build time without a request context, so headers() is not available.