prismicio / prismic-next

Helpers to integrate Prismic into Next.js apps
https://prismic.io/docs/technologies/nextjs
Apache License 2.0
57 stars 7 forks source link

Remove the 404 page flash when previewing an unpublished document via share link #22

Open angeloashmore opened 2 years ago

angeloashmore commented 2 years ago

Is your feature request related to a problem? Please describe.

When using a shared preview link to preview an unpublished document, previewers will see the app's 404 page load and then immediately refresh to the previewed document. This flash of the 404 page is unexpected for most viewers and results in an unpolished viewing experience.

This is the current unpublished preview via share link experience:

  1. Previewer opens the share link.
  2. The link loads a prismic.io URL that sets the preview cookie in the person’s browser.
  3. The prismic.io page redirects to the URL where the share link was created.
  4. Note: it does not redirect to the preview resolver endpoint (/api/preview) where Next.js’s Preview Mode would be activated.
  5. Since the page is not published, the app lands on a 404 URL.
  6. The page sees that a Prismic preview cookie is present, but Next.js Preview Mode is not activated. It fetches the preview resolver endpoint (/api/preview) in the background to start Preview Mode. It then refreshes the page.
  7. Preview Mode is now active, so Next.js runs in SSR mode. It runs getStaticProps() using the preview ref which allows it to query the unpublished document.
  8. The preview is loaded.

Describe the solution you'd like

To remove the flash of the 404 page in this situation, the following flow could be implemented:

  1. Set up the 404 page using getServerSideProps(). This lets the page access the previewer's cookies on the server.
  2. If getServerSideProps() detects that a Prismic preview cookie is present, but Next.js's Preview Mode is not active, we know we need to hit /api/preview.
  3. Redirect to /api/preview with a reference to the current URL (i.e. the previewed page).
  4. Activate Preview Mode in /api/preview like normal.
  5. Redirect back to the previewed page.
  6. The preview is loaded.

Using this flow, the previewer should not see the 404 page. It should result in a quicker time-to-preview since this logic happens on the server. We do not need to wait for the browser to start the current client-side logic that handles this flow.

Describe alternatives you've considered

Additional context

Thanks to @chamois-d-or for surfacing this issue and suggesting solutions. 🙂

chamois-d-or commented 2 years ago

So I just tried on my side, and it's not allowed to add getServerSideProps to 404.js ... https://nextjs.org/docs/messages/404-get-initial-props