vercel/next.js

Server action throws when accessing headers if invoked before hydration

jonathanhefner opened this issue · 2 comments

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/nice-rgb-xsqkxt

To Reproduce

  1. Start the application in development.
  2. Open the preview in a dedicated browser tab.
  3. Disable JavaScript in that tab using the browser's dev console (Chrome instructions; in Firefox, click the cog wheel menu in the upper right corner of the debugger).
  4. Refresh the tab.
  5. On the application root page, click the "Action without headers" button. Notice that the action works and the browser is successfully redirected.
  6. Navigate back.
  7. On the application root page, click the "Action with headers" button. The action does not work. The following error appears in the server log:
     ⨯ Error: `headers` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
        at headers (app/actions.ts:11:16)
       9 |
      10 | export async function actionWithHeaders() {
    > 11 |   (await headers()).get("referer");
         |                ^
      12 |   redirect(`/result/${Date.now()}`);
      13 | }
    

Current vs. Expected behavior

I expect the actionWithHeaders() action to succeed just like the actionWithoutHeaders() action. If for some reason that isn't possible, I expect a more accurate error message (headers is, in fact, being called inside a request scope).

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP PREEMPT_DYNAMIC Sun Aug  6 20:05:33 UTC 2023
  Available memory (MB): 4102
  Available CPU cores: 2
Binaries:
  Node: 20.9.0
  npm: 9.8.1
  Yarn: 1.22.19
  pnpm: 8.10.2
Relevant Packages:
  next: 15.1.1-canary.6 // Latest available version is detected (15.1.1-canary.6).
  eslint-config-next: N/A
  react: 19.0.0
  react-dom: 19.0.0
  typescript: 5.3.3
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Not sure

Which stage(s) are affected? (Select all that apply)

next dev (local)

Additional context

No response

We have similiar issue, but it happens for pages with prefetch.
headers and cookies are in fact called in server actions, but we are getting the same issue and only in production builds only with Next 15

 ⨯ Error: `headers` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
    at headers (app/actions.ts:11:16)

I have a hard times trying to build an easy example for it. However it seems like ALS loosing context between prefetching