vercel / next.js

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

Draft Mode does not work in Middleware #67075

Closed JKarlavige closed 2 months ago

JKarlavige commented 3 months ago

Link to the code that reproduces this issue

https://github.com/JKarlavige/nextjs-draftmode-reproduction

To Reproduce

  1. Clone reproduction repository locally
  2. Install packages with npm i
  3. Run app with npm run dev
  4. In a browser, hit the following url: localhost:3000/api/draft?secret=secret-token&slug=preview-page

Current vs. Expected behavior

Note - Draft mode on the page itself works correctly. draftMode().isEnabled returns true.

Current behavior: In middleware, draftMode().isEnabled returns false after hitting the draft endpoint in step 4 above.

Expected behavior: draftMode().isEnabled should return true after the draft endpoint has been hit.

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.5.0: Wed May  1 20:12:58 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6000
  Available memory (MB): 16384
  Available CPU cores: 10
Binaries:
  Node: 20.11.1
  npm: 10.2.4
Relevant Packages:
  next: 14.2.4 // Latest available version is detected (14.2.4).
  react: 18.3.1
  react-dom: 18.3.1

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

Middleware

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

next dev (local), Vercel (Deployed)

Additional context

On next version 14.1.4 (which we currently use in production), we experience inconsistencies where draft mode in middleware sometimes returns true, and on the following middleware run it returns false.

On version 14.2.4, it appears that draft mode always returns false. middleware-draftmode

coffeecupjapan commented 3 months ago

@JKarlavige Hi. I am not quite understand implementation of draft mode, but it seems like isEnable is readonly and no chance to be updated when enable() or disable() is called.

https://github.com/vercel/next.js/blob/c839d589abf95d248398848081b8194e0d3aed5c/packages/next/src/server/async-storage/draft-mode-provider.ts#L40-L45

May be you can use request.cookies.has('__prerender_bypass') to test whether draft mode is enabled or not.

https://github.com/vercel/next.js/issues/52080#issuecomment-1785039348

taylor-lindores-reeves commented 2 months ago

Quick question on Draft Mode - does it require integration of a Headless CMS or can we use it without one?

github-actions[bot] commented 2 months 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.