vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.25k stars 27.02k forks source link

Cannot enable Draft Mode in Middleware #52557

Closed CMeeg closed 1 year ago

CMeeg commented 1 year ago

Verify canary release

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Pro
Binaries:
  Node: 18.16.1
  npm: 9.5.1
  Yarn: N/A
  pnpm: 8.5.1
Relevant Packages:
  next: 13.4.10-canary.3
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 4.9.5
Next.js Config:
  output: N/A

Which area(s) of Next.js are affected? (leave empty if unsure)

Middleware / Edge (API routes, runtime)

Link to the code that reproduces this issue or a replay of the bug

https://github.com/CMeeg/nextjs-middleware-draftmode

To Reproduce

Using the minimal repro:

Describe the Bug

I want to enable Draft Mode from within Middleware. More specifically in the Middleware I am trying to:

I am aware from the examples in the Draft Mode docs that typically draft mode is enabled via API routes, but Middleware seemed like a better choice for me as I can validate the data already present in the querystring of the request rather than having to go to an API route first and then redirect to the actual location.

As Draft Mode is configured based on a cookie and you can set cookies from within Middleware I thought this would be possible, but the draftMode function from next/headers throws an error if you try to use it within Middleware, Error: Invariant: Method expects to have requestAsyncStorage, none available.

I noticed also that while the code examples in the Draft Mode documentation all use this draftMode function, there are a lot of examples (e.g. cms-storyblok that show another function available on NextApiResponse called setDraftMode, but that is not available within Middleware.

It seems like setting the Draft Mode cookie from within Middleware should be possible, but I cannot find any way to do so.

Expected Behavior

I would like some way of setting the Draft Mode cookie from within Middleware so that Draft Mode can be enabled and used when fetching data from a page/layout/component within a single request.

Which browser are you using? (if relevant)

Chrome 114.0.5735.198

How are you deploying your application? (if relevant)

No response

github-actions[bot] commented 1 year ago

This closed issue has been automatically locked because it had no new activity for 2 weeks. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.